使用gson在java中反序列化嵌套的任意类

时间:2012-08-13 13:19:33

标签: java json arraylist gson nested-class

我需要转换json-string tmp => 的 { “RESULT_COUNT”:1, “next_offset”:1, “entry_list”:[{ “ID”: “XYZ123”, “模块名”: “产品”, “name_value_list”:{ “ID”:{“名“:” ID”, “值”: “XYZ123”}, “名称”:{ “名称”: “姓名”, “值”: “test_product_2”}}}], “relationship_list”:[]} 进入相应的java-pojo

我的pojo看起来像

public class GetEntryListResponse {

public int result_count = 0;
public int next_offset = 0;
public List<EntryList> entryList = new ArrayList<EntryList>();
public static class EntryList {
    String id = "";
    String module_name = "";
    public static class NameValueList {
        public static class Id {
            String name = "";
            String value = "";
        }
        public static class Name {
            String name = "";
            String value = "";
        }
    }
}
}

和deserilizing-task使用

Gson json_response = new Gson();
GetEntryListResponse resp = json_response.fromJson(tmp, 
                                                   GetEntryListResponse.class);

我也尝试了其他变种,但到目前为止这个似乎是最好的。问题是result_count和next_offset被转换为int,但数组entryList的类型是null值。

2 个答案:

答案 0 :(得分:0)

为您的班级实施InstanceCreator和JsonDeserializer

  public class GetEntryListResponse implements
            InstanceCreator<GetEntryListResponse>,
            JsonDeserializer<GetEntryListResponse>{

    @Override
        public GetEntryListResponse createInstance(Type type) {
            return this;
        }

    @Override
        public GetEntryListResponse deserialize(JsonElement json, Type typeOfT){
      json.getJsonObject();// 
    // create your classes objects here by json key
    }

并使用

GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.registerTypeAdapter(GetEntryListResponse.class,
                new GetEntryListResponse()).create();

答案 1 :(得分:0)

尝试改变:

public List<EntryList> entryList = new ArrayList<EntryList>();

为:

public List<EntryList> entry_list= new ArrayList<EntryList>();

并反序列化。