Gson反序列化与不断变化的字段类型

时间:2016-07-15 10:07:01

标签: java json gson deserialization

我得到一个具有以下结构的JSON:

{"field1": "string",
"field2": false,
"a": {
    "b": {
        "listString": []
    },
    "c": {
        "listString": [],
        "s": "string"
    },
    "parent": {
        "childA": {
            "listString": ["string", "string"]
        },
        "s": "string"
    },
    "parent2": {
        "listString": ["string", "string"],
        "s": "string"
    }
},
"field3": ["s", "s"]
}

我遇到parent(和parent2)的问题,因为这些字段的格式可能会发生变化。虽然复杂对象bc的格式保持不变。例如,我可以通过这种方式获得parent(同样适用于parent2):

{"parent": {
    "childA":{
        "listString": ["ssssa", "a"]
         },
     "s": "string"
}}

{"parent": {
    "listString": ["ssssa", "a"],
    "s": "string"
}}

此外,childA字段(如果存在)可以有不同的名称,可以是childBchildC

我为复杂对象创建了java类:

public class MyPojo{
  private String[] field1;
  private String field2;
  private A a;
  private String field3;...}

public class A{
  private B b;
  private C c;
  private Parent parent;
  private Parent2 parent2;..}

public class Parent{
  private String s;
  private ChildA childA;...}...

如果parentparent2对象有不同的格式,我如何用Gson反序列化这样的东西?

1 个答案:

答案 0 :(得分:0)

这是父类:

public class Parent {
Map<String, JsonElement> parent = null;

public Map<String, JsonElement> getParent() {
    return parent;
}

public void setParent(Map<String, JsonElement> parent) {
    this.parent = parent;
}

}

这是主要课程:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String input = "{\"parent\": {\"s\": \"string\",\"childA\":{\"listString\": [\"ssssa\", \"a\"]}}}";
    Gson gsonInstance = null;

    gsonInstance = new GsonBuilder().create();

    Parent p = gsonInstance.fromJson(input, Parent.class);

    Map<String, JsonElement> parentMap = p.getParent();
    Set<String> keyMap = parentMap.keySet();

    Iterator<String> iter = keyMap.iterator();
    while(iter.hasNext()){
        String name = iter.next();
        if(name.matches("child(.*)")){
            System.out.println(parentMap.get(name));
            // do your logic
        }
        if (keyMap.contains("listString")){
            List<String> listString = getListString(parentMap.get("listString"));
            System.out.println(listString.toString());
        }
    }

}

public static List<String> getListString(JsonElement list){
    Type listType = new TypeToken<List<String>>() {}.getType();
    List<String> listString = new Gson().fromJson(list, listType);
    return listString;
}

希望它有所帮助!