我必须像这样反序列化json:
{
"key1" : [
{
"hash1" : "value1_1",
"hash2" : "value1_2",
...
"hashN" : "value1_3",
"date" : "dateValue1"
},
{
"hash1" : "value2_1",
"hash2" : "value2_2",
...
"hashN" : "value2_3",
"date" : "dateValue2"
},
...
],
"key2": {
"description" : {
"hash1" : {
"description1" : "some text",
"description2" : "some text",
},
...
"hashN" : {
"description1" : "some text",
"description2" : "some text",
}
}
}
}
json有一组未知密钥:hash1,hash2,... hash2和一组已知密钥:key1,key2,description,date,description1,description2。
我使用一些自定义rest客户端,它使用默认的GSON配置将jsons反序列化为对象。我无法改变这种配置。 使用此休息客户端如下所示:
restClient.makeRequest(requestData, DataResponse.class, new RestResponseListener<DataResponse>()
{
@Override
public void onSuccessfulResponse(DataResponse responseData)
{
}
});
DataResponse类必须从rest客户端包继承Response类。
其余客户端不能像上面那样反序列化jsons所以我决定尝试反序列化为String或JsonObject,然后在onSuccessfulResponse
中使用自定义反序列化器。
我尝试创建下面的类以保持响应:
public class DataResponse extends Response
{
private String key1;
private String key2;
public DataResponse()
{
}
}
不幸的是我得到了例外:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 14 path
问题是,如何将key1和object中的数组从key2反序列化为字符串。
或许是另一种解决方案。
答案 0 :(得分:0)
按照Lyubomyr Shaydariv的建议,我找到了两个解决方案。
JsonElement
当然是抽象的,所以我必须使用如下的子类
public class DataResponse extends Response
{
private JsonArray key1;
private JsonObject key2;
public DataResponse()
{
}
//getters
}
在休息客户端回调中,我处理了这样的数据:
restClient.makeRequest(requestData, DataResponse.class, new RestResponseListener<DataResponse>()
{
@Override
public void onSuccessfulResponse(DataResponse responseData)
{
Type mapType = new TypeToken<Map<String, String>>(){}.getType();
Gson gson = new Gson();
for(JsonElement element : responseData.getKey1())
{
Map<String, String> map = gson.fromJson(element, mapType);
//do things
}
}
});
我不知道为什么它以前不起作用,但现在确实:
public class DataResponse extends Response
{
private List<Map<String, String>> key1;
private Key2SchemaClass key2;
public DataResponse()
{
}
public static class Key2SchemaClass
{
private List<Map<String, Description>> description;
}
public static class Description
{
private String description1;
private String description2;
}
//getters
}