简体   繁体   English

嵌套数组的GSON解析

[英]GSON parsing of nested array

Im having difficulties understanding if GSON can handle this kind of json by default or do I need to implement deserializers for every sub element. 我在理解GSON是否可以默认处理此类json时遇到困难,还是我需要为每个子元素实现反序列化器。

json input json输入

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

The best case result on my part is to have the following class contain all the data 我最好的情况是让以下类包含所有数据

java [ POJO ] 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;
    }
}

Is it possible to let GSON the class and the json and just let it work? 是否可以让GSON作为类和json并使其正常工作? Or do I need to create deserializers for each sub class? 还是我需要为每个子类创建反序列化器?

Correct your json input as follow (you forgot a comma before status field) 更正您的json输入,如下所示(您在status字段前忘记了逗号)

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

Then let's consider your classes as follow 然后让我们考虑以下课程

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

If the input is a file jsonInput.json then 如果输入是文件jsonInput.json

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

If the input is a json String jsonInput then 如果输入是json字符串jsonInput

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

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM