【发布时间】:2014-08-06 15:06:04
【问题描述】:
我正在尝试解析具有以下格式的 JSON 字符串:
{
"request" : {
"Format" : "json",
"Method" : "method",
"NetworkId" : "net",
"NetworkToken" : "token",
"Service" : "service",
"Target" : "target",
"Version" : "2"
},
"response" : {
"data" : {
"1315" : {
"AffiliateUser" : {
"id" : "1315"
}
}
},
"errorMessage" : null,
"errors" : [ ],
"httpStatus" : 200,
"status" : 1
}
}
使用此代码:
public class AffiliateIdResponse{
private Map<String, Map<String, Map<String, Map<String, String>>>> data;
public static AffiliateIdResponse fromJson(String jsonString) {
Type mapType = new TypeToken<Map<String, Map<String, Map<String, Map<String, String>>>>>() {
}.getType();
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(mapType, new Gson().getAdapter(TypeToken.get(mapType)));
return gsonBuilder.create().fromJson(jsonString, AffiliateIdResponse.class);
}
public static AffiliateIdResponse handleResponse(MyHttpResponse httpResponse) {
AffiliateIdResponse response = null;
if (httpResponse.getStatusCode() == MyHttpStatus.OK
|| httpResponse.getStatusCode() == MyHttpStatus.ACCEPTED
|| httpResponse.getStatusCode() == MyHttpStatus.CREATED) {
response = fromJson(httpResponse.getBody());
} else {
response = new AffiliateIdResponse();
}
response.setHttpResponseData(httpResponse);
return response;
}
}
但名为 data 的字段始终为空。如果我改为这样做:
public class AffiliateIdResponse{
public static AffiliateIdResponse fromJson(String jsonString) {
Type mapType = new TypeToken<Map<String, Map<String, Map<String, Map<String, String>>>>>() {
}.getType();
Map<String, Map<String, Map<String, Map<String, String>>>> map = null;
map = new Gson().fromJson("{ \"data\": { \"1315\": { \"AffiliateUser\": {" +
"\"id\":\"1315\"}}}}", mapType);
}
public static AffiliateIdResponse handleResponse(MyHttpResponse httpResponse) {
AffiliateIdResponse response = null;
if (httpResponse.getStatusCode() == MyHttpStatus.OK
|| httpResponse.getStatusCode() == MyHttpStatus.ACCEPTED
|| httpResponse.getStatusCode() == MyHttpStatus.CREATED) {
response = fromJson(httpResponse.getBody());
} else {
response = new AffiliateIdResponse();
}
response.setHttpResponseData(httpResponse);
return response;
}
}
名为 map 的值实际上将包含我想要的数据。为什么使用第一种方法时这不起作用?
【问题讨论】:
-
你能和我们分享一下 AffiliateIdResponse 对象吗?
-
@Leo 我认为这并不重要,因为 json 解析是在 fromJson 方法中完成的,但我已经更新为包含整个类。