繁体   English   中英

使用GSON获取嵌套的JSON对象:反序列化

[英]Get nested JSON object with GSON : Deserialization

我遍历了SOF的线程,该线程讨论了如何使用GSON获得嵌套的JSON。 链接1 链接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);

问题:

我的Subparent元素(例如'Employee_1')不断变化。 我必须构造多个解串器吗?

另外,当我们使用nestedJSON时,我了解到“期望一个字符串,但是是BEGIN_OBJECT”。

我不确定您的类如何转换为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]]

暂无
暂无

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

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