Gson and only concentrate on inner object

拥有回忆 提交于 2019-12-13 02:54:59

问题


Ok I have a json coming in that looks like this:

{count:xxx, important:[{...}]}

All I care about is the important object. Is there anything I can do with a custom deserializer or anything where I can just have GSON deserialize that important json object?

Also the way I want the deserialized object to look is like this:

List<Important> = Gson.fromJson(arg0, new TypeToken<ArrayList<Important>>(){}.getType() );

回答1:


Yes, you can use the JsonParser class from the Gson library to read it as a JsonObject. Then, pull out the inner object you need and use Gson to fill your java class with it.

Example:

Reader jsonReader =
                new BufferedReader(
                new InputStreamReader(getIStream("myFile.json")));
JsonParser parser = new JsonParser();
JsonObject top = parser.parse(jsonReader).getAsJsonObject();

JsonElement importantEl = top.get("important");

//Parse the important element into whatever structure you're creating
Gson gson = new Gson();
List<Important> important 
    = Gson.fromJson(importantEl, new TypeToken<ArrayList<Important>>(){}.getType() );


来源:https://stackoverflow.com/questions/12825229/gson-and-only-concentrate-on-inner-object

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