我正在尝试编写一个实用程序方法,我可以在代码中的任何地方使用它来检索json的某些部分。这是我的方法:
public static <T> T getResponseObject(String resourceResponse, String jsonField, Class<T> responseClass) {
T responseObject = null;
try {
JSONObject jsonResponse = new JSONObject(resourceResponse).getJSONObject(jsonField);
responseObject = mapper.readValue(jsonResponse.toString(), TypeFactory.defaultInstance().constructType(responseClass));
} catch(IOException e) {
LOGGER.error("IO error, cannot read json response", e);
e.printStackTrace();
} catch(JSONException e) {
LOGGER.error("JSON API error", e);
e.printStackTrace();
}
return responseObject;
}
以下是JSON响应示例:
{
"User":{
"identityList":{
"identity":[
{
"firstName":"MICHAEL",
"lastName":"JAMESON",
"gender":"MALE",
"dateOfBirth":"1961-05-18T00:00:00.000+0000",
},
{
"firstName":"KELLY",
"lastName":"JAMESON",
"gender":"FEMALE",
"dateOfBirth":"1951-04-01T00:00:43.000+0000",
}
]
}
},
"resultCode": true
}
因此,如果我想获得identity
字段,我必须遍历3层才能获得数组。我知道如何解决这个问题,方法是将方法输入设置为List<String>
,如下所示:
+-------+--------------+
| Index | Value |
+-------+--------------+
| 0 | User |
| 1 | identityList |
| 2 | identity |
+-------+--------------+
我会迭代这个列表直到我到达最后一个字段。但是,这似乎并不是最好的方法。无论如何都要在1次调用中访问嵌套字段,在这种情况下是identity
,而不必通过多次getJSONObject
调用来遍历?
答案 0 :(得分:0)
这里尝试这样的事情。我喜欢在java中使这样的json,因为它很容易做,并且易于阅读你正在做的事情
jsonResponseObject.getJSONObject(“User”).getJSONObject(“identityList”).getJSONArray(“identity”);
你可以用这个做你想做的事。关于如何使用它的示例;
myInt = jsonObject.getJSONObject("Level1").getInt("myInt");