
我采用了答案,以介绍聊天中设计的完整解决方案并适合更改后的JSON字符串。该代码假定字符串json完全包含问题中的(更新的)JSON。要求是填充以下类(省略setter和toString):
class Object1{ private String attribute1; private String attribute40; private int userId; private String nameList;}GSON支持(与大多数其他REST库一样)三种模式:
GSON_DOM
通过读取整个JSONJsonParser.parse()
并在内存中构建DOM树(对象模型访问)。因此,此解决方案适用于小型JSON文件。GSON_STREAM通过
读取JSON的大块JsonReader
。代码更加复杂,但是它适用于大型JSON文件。从Android 3.0
Honeycomb开始,GSON的流解析器包含为android.util.JsonReader
。GSON_BIND
通过反射将数据直接绑定到类,从而极大地减少了代码。GSON允许使用混合模式,这意味着应结合该答案显示的GSON_DOM和GSON_BIND或GSON_STREAM和GSON_BIND。
通过GSON_DOM和GSON_BIND填充类Object1,实现如下所示:
private static void deserializeViaObjectAccess(final String json){ Gson gson = new Gson(); // Read the whole JSON into meomory via GSON_DOM JsonParser parser = new JsonParser(); JsonObject object1 = parser.parse(json).getAsJsonObject().getAsJsonObject("object1"); // map the Object1 class via GSON_BIND // (bind common attributes which exist in JSON and as properties in the class) // mapper acts as factory Object1 result = gson.fromJson(object1, Object1.class); // manually read the attribute from the user object int userId = object1.getAsJsonObject("user").getAsJsonPrimitive("id").getAsInt(); result.setUserId(userId); // manually read the attributes from the example object String names = ""; JsonArray list = object1.getAsJsonObject("example").getAsJsonArray("list"); for (int i = 0; i < list.size(); ++i) { JsonObject entry = list.get(i).getAsJsonObject(); String name = entry.getAsJsonPrimitive("name").getAsString(); names = i == 0 ? name : names + "; " + name; } result.setNameList(names); // Output the result log.debug(result.toString());}通过GSON_STREAM和GSON_BIND填充类Object1,实现如下:
目前,这仅在通过GSON_BIND或GSON_STREAM完全加载节点时才可行。此示例需要拆分节点本身。这仅在即将发布的2.2版中可行。当GSON
2.2可用时,我将交出代码。*
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)