Using Gson and JsonObject to format and parse data

拈花ヽ惹草 提交于 2019-12-20 20:18:13

问题


I am using JsonObject and Gson to format the data i need to send in the form of String and then retrieve and parse it somewhere else. This is my simple code which is not working:

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


}

What am i doing wrong here?


回答1:


You should use:

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

Lots of calls in there, but the gist is to use the JsonParser class.



来源:https://stackoverflow.com/questions/13434819/using-gson-and-jsonobject-to-format-and-parse-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!