简体   繁体   English

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

[英]deserialize nested arbitrary class in java with gson

i need to convert the json-string tmp => {"result_count":1,"next_offset":1,"entry_list":[{"id":"xyz123","module_name":"Products","name_value_list":{"id":{"name":"id","value":"xyz123"},"name":{"name":"name","value":"test_product_2"}}}],"relationship_list":[]} into a corresponding java-pojo 我需要转换json-string tmp => {“ result_count”:1,“ next_offset”:1,“ entry_list”:[{“ id”:“ xyz123”,“ module_name”:“产品”,“ name_value_list”: {“ id”:{“ name”:“ id”,“ value”:“ xyz123”},“ name”:{“ name”:“ name”,“ value”:“ test_product_2”}}}]],“ relationship_list “:[]}转换为相应的java-pojo

my pojo looks like 我的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 = "";
        }
    }
}
}

and for the deserilizing-task a use 并用于反杀菌任务

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

i also tried other variants but this one seems to be the best so far. 我也尝试了其他变种,但是这似乎是迄今为止最好的。 the problem is that result_count and next_offset are transformed into int but the type of the array entryList is with null-values. 问题是将result_count和next_offset转换为int,但是数组entryList的类型为空值。

Implement InstanceCreator and JsonDeserializer for your class 为您的类实现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
    }

and use 和使用

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

try changing: 尝试更改:

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

to: 至:

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

and deserialize. 并反序列化。

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

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