在安卓中使用GSON/Jackson

3

我能够使用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",        
    }
}

1
也许您可以包含您尝试过的POJO定义,以便了解可能出了什么问题?基本思路就是匹配结构。 - StaxMan
此外,在发布问题时,我建议您付出努力确保任何代码或JSON示例都是有效和正确的。原始问题中的JSON示例无效,让可能帮助或从此线程学习的人猜测其中的内容。可以使用http://jsonlint.com 快速轻松地验证JSON。 - Programmer Bruce
1个回答

8
以下是使用Gson和Jackson将JSON(类似于原问题中的无效JSON)反序列化/序列化为匹配的Java数据结构的简单示例。 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));
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接