【问题标题】:GSON/Jackson in AndroidAndroid 中的 GSON/杰克逊
【发布时间】:2011-10-29 14:51:36
【问题描述】:

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

【问题讨论】:

  • 也许您可以包含您尝试过的 POJO 定义,以了解可能出了什么问题?基本思想就是匹配结构。
  • 另外,在发布问题时,我建议您努力确保任何代码或 JSON 示例都是有效且正确的。原始问题中的 JSON 示例是无效的,并且可能会帮助或从该线程中学习的人猜测是什么。 jsonlint.com 可用于快速轻松地验证 JSON。

标签: java android json gson jackson


【解决方案1】:

以下是使用 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;
}

杰克逊示例:

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));
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    相关资源
    最近更新 更多