GSON解析嵌套数组

时间:2015-05-17 09:17:13

标签: java json gson

我很难理解GSON是否可以默认处理这种json,或者我是否需要为每个子元素实现反序列化。

json输入

{
   "services":[
      {
         "id": 2,
         "name": "Buy"
      },
      {
         "id": 3,
         "name": "Sell"
      }
      ]
   "status": {
      "code": 0,
      "message": ""
   }
}

我的最佳案例结果是让以下类包含所有数据

java [POJO]

public class Services {
    public List<ServiceItem> services;
    public Status status;

    public class ServiceItem {
        public int id;
        public String name;
    }

    public class Status {
        public int code;
        public String message;
    }
}

是否可以让GSON成为类和json并让它工作?或者我是否需要为每个子类创建反序列化器?

1 个答案:

答案 0 :(得分:2)

更正您的json输入,如下所示(您忘记了status字段前的逗号)

{
   "services":[
      {
         "id": 2,
         "name": "Buy"
      },
      {
         "id": 3,
         "name": "Sell"
      }
      ],
   "status": {
      "code": 0,
      "message": ""
   }
}

然后让我们将您的课程视为

public class Services {
    public List<ServiceItem> services;
    public Status status;
    // getters and setters
    @Override
    public String toString() {
        return "["+services.toString()+status.toString()+"]";
    }

    public class ServiceItem {
        public int id;
        public String name;
        // getters and setters
        @Override
        public String toString() {
            return "("+id+","+name+")";
        }

    }

    public class Status {
        public int code;
        public String message;
        // getters and setters
        @Override
        public String toString() {
            return ",("+code+","+message+")";
        }
    }
}

如果输入是文件jsonInput.json,那么

Gson gson = new Gson();
Services data = gson.fromJson(new BufferedReader(new FileReader(
        "jsonInput.json")), new TypeToken<Services>() {
}.getType());
System.out.println(data);

如果输入是json String jsonInput,那么

Gson gson = new Gson();
Services data = gson.fromJson(jsonInput, Services.class);
System.out.println(data);

输出:

[[(2,Buy), (3,Sell)],(0,)]