我的Android应用程序中有以下JSON,我使用Springs for android RestTemplate
。是否有可能从这个json中获取内部列表?目前我必须创建一个包装器对象,然后我可以从中获取List<Cast> casts;
- 它有点不方便。
{
"id": 550,
"cast": [
{
"cast_id": 4,
"character": "The Narrator",
"credit_id": "52fe4250c3a36847f80149f3",
"id": 819,
"name": "Edward Norton",
"order": 0,
"profile_path": "/iUiePUAQKN4GY6jorH9m23cbVli.jpg"
}
]
}
答案 0 :(得分:0)
我知道有两个解决方案可以解决这个问题:
但我认为最终的解决方案是在这篇文章中: Spring/json: Convert a typed collection like List<MyPojo>
答案 1 :(得分:0)
如果Cast
是POJO,您可以尝试使用像这样的Jackson ObjectMapper
ObjectMapper mapper = new ObjectMapper();
String jsonStr = ...
List<Cast> casts = mapper.readValue(jsonStr, new TypeReference<List<Cast>>(){});
答案 2 :(得分:0)
您可以抓住字段,强制转换并将其转换为:
final String json = "{\n" +
" \"id\": 550,\n" +
" \"cast\": [\n" +
" {\n" +
" \"cast_id\": 4,\n" +
" \"character\": \"The Narrator\",\n" +
" \"credit_id\": \"52fe4250c3a36847f80149f3\",\n" +
" \"id\": 819,\n" +
" \"name\": \"Edward Norton\",\n" +
" \"order\": 0,\n" +
" \"profile_path\": \"/iUiePUAQKN4GY6jorH9m23cbVli.jpg\"\n" +
" }\n" +
" ]\n" +
"}";
final List<Cast> casts;
try {
final JsonNode cast = objectMapper.readTree(json).get("cast");
casts = objectMapper.convertValue(cast, new TypeReference<List<Cast>>() {});
} catch (IOException e) {
throw Throwables.propagate(e);
}