【问题标题】:Using Gson and JsonObject to format and parse data使用 Gson 和 JsonObject 格式化和解析数据
【发布时间】:2012-11-06 06:06:25
【问题描述】:

我正在使用JsonObjectGson 来格式化我需要以字符串形式发送的数据,然后在其他地方检索和解析它。 这是我的简单代码,它不起作用:

public static void main(String[] args) 
{

    Gson g = new Gson();
    Gson listG = new Gson();
    ArrayList<String> l= new ArrayList<String>();
    l.add("abcd");
    l.add("efgh");
    l.add("ijkl");

    String list = listG.toJson(l);

    JsonObject jObject = new JsonObject();
    jObject.addProperty("command" , 1);
    jObject.addProperty("message" , "this is a test message");
    jObject.addProperty("list" , list);

    String toSend = g.toJson(jObject);
    System.out.println(toSend);  

    Gson rec = new Gson();
    JsonObject newObj = rec.fromJson(toSend, JsonObject.class);
    System.out.println(newObj);  // getting nothing in newObj


}

我在这里做错了什么?

【问题讨论】:

    标签: json parsing gson


    【解决方案1】:

    你应该使用:

    JsonObject newObj = new JsonParser().parse(toSend).getAsJsonObject();
    

    那里有很多电话,但要点是使用JsonParser 类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-10
      • 1970-01-01
      • 2012-06-07
      • 1970-01-01
      相关资源
      最近更新 更多