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

用gson反序列化java中嵌套的任意类,java,json,arraylist,gson,nested-class,Java,Json,Arraylist,Gson,Nested Class,我需要转换json字符串tmp=> {“结果计数”:1,“下一个偏移量”:1,“条目列表”:[{“id”:“xyz123”,“模块名称”:“产品”,“名称/值列表”:{“id”:{“名称”:“id”,“值”:“xyz123”},“名称”:“名称”:“名称”,“值”:“测试产品2”}}],“关系列表”:[]} 转换为相应的JavaPOJO 我的pojo看起来像 public class GetEntryListResponse { public int result_count = 0; pub

我需要转换json字符串tmp=> {“结果计数”:1,“下一个偏移量”:1,“条目列表”:[{“id”:“xyz123”,“模块名称”:“产品”,“名称/值列表”:{“id”:{“名称”:“id”,“值”:“xyz123”},“名称”:“名称”:“名称”,“值”:“测试产品2”}}],“关系列表”:[]} 转换为相应的JavaPOJO

我的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 = "";
        }
    }
}
}

我也尝试了其他的变体,但这一个似乎是迄今为止最好的。问题是结果计数和下一个偏移量被转换为int,但数组entryList的类型具有空值。

为类实现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
    }
尝试更改:

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

public List entry_List=new ArrayList();

和反序列化。

您在混合样式:
result\u count
entryList
不能一起使用(除非您在Json中使用相同的混乱)。我看不到你在使用任何
FieldNamingStrategy
,所以我想知道它是如何工作的。这毫无意义。我看不出在这里创建实例有任何问题,也不需要自定义反序列化。我不明白为什么类本身应该被用作
InstanceCreator
和/或
JsonDeserializer
(这不是一种糟糕的样式吗?)。正如第二篇文章中提到的,将entryList更改为entry\u list起到了作用。但我认为你的建议是最好的。如果我在中再次遇到这个问题,我想我会使用@yahor10提到的自定义反序列化程序。将entryList更改为entry_list不知何故成功了。我还将类结构从静态类更改为基于实例的类。仍然不明白为什么会这样,因为根据gson用户指南,任意类都应该以静态方式使用
GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.registerTypeAdapter(GetEntryListResponse.class,
                new GetEntryListResponse()).create();
public List<EntryList> entryList = new ArrayList<EntryList>();
public List<EntryList> entry_list= new ArrayList<EntryList>();