【问题标题】:Get nested JSON object with GSON : Deserialization使用 GSON 获取嵌套的 JSON 对象:反序列化
【发布时间】:2016-11-16 11:57:25
【问题描述】:

我已经阅读了 SOF 中关于使用 GSON 获取嵌套 JSON 的线程。 Link 1Link 2。我的 JSON 文件如下图所示

{
   "Employee_1": {
      "ZipCode": 560072,
      "Age": 50,
      "Place": "Hawaii",
      "isDeveloper": true,
      "Name": "Mary"
   },
   "Employee_2": {
      "ZipCode": 560072,
      "Age": 80,
      "Place": "Texas",
      "isDeveloper": true,
      "Name": "Jon"
   }
}

我的班级如下图

public class Staff {

    String Employee_1 ; 
}

class addnlInfo{
    String Name;
    String Place;
    int Age;
    int Zipcode;
    boolean isDeveloper;
}  

我构建的反序列化器类如下图

class MyDeserializer implements JsonDeserializer<addnlInfo>{

    public addnlInfo deserialize1(JsonElement je, Type type, JsonDeserializationContext jdc)
        throws JsonParseException
    {
        // Get the "content" element from the parsed JSON
        JsonElement content = je.getAsJsonObject().get("Employee_1");

        // Deserialize it. You use a new instance of Gson to avoid infinite recursion
        // to this deserializer
        return new Gson().fromJson(content, addnlInfo.class);

    }

    @Override
    public TokenMetaInfo deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        // TODO Auto-generated method stub
        return null;
    }

主文件

Gson gson = new GsonBuilder()
                .registerTypeAdapter(addnlInfo.class, new MyDeserializer())
                .create();

String jsonObject=  gson.toJson(parserJSON);
addnlInfo info= gson.fromJson(jsonObject, addnlInfo .class);
System.out.println(info.Age + "\n" + info.isDeveloper + "\n" + info.Name + "\n" + info.Place);


Staff parentNode = gson.fromJson(jsonObject, Staff.class);
System.out.println(parentNode.Employee_1);

问题:

我的子父元素(例如“Employee_1”)不断变化。我必须构建多个反序列化器吗?

此外,当我们使用nestedJSON 时,我得到“预期为字符串,但为 BEGIN_OBJECT”。

【问题讨论】:

    标签: java json serialization gson


    【解决方案1】:

    我不确定你的类是如何转换成 JSON 的,但是你把它弄得太复杂了。

    我重命名了字段和类名以符合 Java 标准。

    Main.java

    import java.lang.reflect.Type;
    import java.util.LinkedHashMap;
    import java.util.Map;
    import java.util.Map.Entry;
    
    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    import com.google.gson.reflect.TypeToken;
    
    public class Main {
        public static void main(String[] args) {
            Map<String, Staff> employees = new LinkedHashMap<String, Staff>();
            employees.put("Employee_1", new Staff(new Info("Mary", "Hawaii", 50, 56072, true)));
            employees.put("Employee_2", new Staff(new Info("Jon",  "Texas",  80, 56072, true)));
    
            String jsonString = new GsonBuilder().setPrettyPrinting().create().toJson(employees);
            System.out.println("# SERIALIZED DATA:");
            System.out.println(jsonString);
    
            Type mapOfStaff = new TypeToken<Map<String, Staff>>() {}.getType();
            Map<String, Staff> jsonObject = new Gson().fromJson(jsonString, mapOfStaff);
            System.out.println("\n# DESERIALIZED DATA:");
            for (Entry<String, Staff> entry : jsonObject.entrySet()) {
                System.out.printf("%s => %s%n", entry.getKey(), entry.getValue());
            }
        }
    }
    

    Staff.java

    public class Staff {
        private Info info;
    
        public Staff(Info info) {
            this.info = info;
        }
    
        public Info getInfo() {
            return info;
        }
    
        public void setInfo(Info info) {
            this.info = info;
        }
    
        @Override
        public String toString() {
            return String.format("Staff [info=%s]", info);
        }
    }
    

    Info.java

    public class Info {
        private String name;
        private String place;
        private int age;
        private int zipcode;
        private boolean developer;
    
        public Info(String name, String place, int age, int zipcode, boolean developer) {
            this.name = name;
            this.place = place;
            this.age = age;
            this.zipcode = zipcode;
            this.developer = developer;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getPlace() {
            return place;
        }
    
        public void setPlace(String place) {
            this.place = place;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public int getZipcode() {
            return zipcode;
        }
    
        public void setZipcode(int zipcode) {
            this.zipcode = zipcode;
        }
    
        public boolean isDeveloper() {
            return developer;
        }
    
        public void setDeveloper(boolean developer) {
            this.developer = developer;
        }
    
        @Override
        public String toString() {
            return String.format(
                "Info [name=%s, place=%s, age=%d, zipcode=%d, developer=%b]",
                name, place, age, zipcode, developer
            );
        }
    }
    

    输出

    # SERIALIZED DATA:
    {
      "Employee_1": {
        "info": {
          "name": "Mary",
          "place": "Hawaii",
          "age": 50,
          "zipcode": 56072,
          "developer": true
        }
      },
      "Employee_2": {
        "info": {
          "name": "Jon",
          "place": "Texas",
          "age": 80,
          "zipcode": 56072,
          "developer": true
        }
      }
    }
    
    # DESERIALIZED DATA:
    Employee_1 => Staff [info=Info [name=Mary, place=Hawaii, age=50, zipcode=56072, developer=true]]
    Employee_2 => Staff [info=Info [name=Jon, place=Texas, age=80, zipcode=56072, developer=true]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-05
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-30
      相关资源
      最近更新 更多