0

我需要转换 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 ":[]} 转换成对应的 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 的类型为空值。

4

2 回答 2

0

尝试改变:

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

至:

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

并反序列化。

于 2012-08-13T13:48:32.763 回答
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();
于 2012-08-13T13:31:24.770 回答