Android中的GSON / Jackson

我能够使用JSONObject和JSONArray在Android中成功解析下面的JSON字符串。 没有成功与GSON或jackson达成相同的结果。 有人可以帮助我使用包含POJO定义的代码片段来解析GSON和Jackson吗?

{ "response":{ "status":200 }, "items":[ { "item":{ "body":"Computing" "subject":"Math" "attachment":false, } }, { "item":{ "body":"Analytics" "subject":"Quant" "attachment":true, } }, ], "score":10, "thesis":{ "submitted":false, "title":"Masters" "field":"Sciences", } } 

以下是使用Gson和Jackson对匹配的Java数据结构进行反序列化/序列化JSON(类似于原始问题中的无效JSON)的简单示例。

JSON:

 { "response": { "status": 200 }, "items": [ { "item": { "body": "Computing", "subject": "Math", "attachment": false } }, { "item": { "body": "Analytics", "subject": "Quant", "attachment": true } } ], "score": 10, "thesis": { "submitted": false, "title": "Masters", "field": "Sciences" } } 

匹配的Java数据结构:

 class Thing { Response response; ItemWrapper[] items; int score; Thesis thesis; } class Response { int status; } class ItemWrapper { Item item; } class Item { String body; String subject; boolean attachment; } class Thesis { boolean submitted; String title; String field; } 

jackson示例:

 import java.io.File; import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility; import org.codehaus.jackson.map.ObjectMapper; public class JacksonFoo { public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.setVisibilityChecker( mapper.getVisibilityChecker() .withFieldVisibility(Visibility.ANY)); Thing thing = mapper.readValue(new File("input.json"), Thing.class); System.out.println(mapper.writeValueAsString(thing)); } } 

Gson示例:

 import java.io.FileReader; import com.google.gson.Gson; public class GsonFoo { public static void main(String[] args) throws Exception { Gson gson = new Gson(); Thing thing = gson.fromJson(new FileReader("input.json"), Thing.class); System.out.println(gson.toJson(thing)); } }