嗨,我是新手使用json文件,我完全迷失了。我有一个包含多个数组的jsonobject,需要从所有数组中获取key title的值以填充listview。我知道如何通过名称获取单个数组的值,但不知道从哪里开始从多个数组获取值而不使用名称。任何帮助都会受到极大的赞赏,因为我已经有大量的例子,似乎没有一个适合我想做的事情。
我的json代码
{
"1":[{"gameid":"1","title":"This Game","more stuff":"stuff 1"}]
,"2":[{"gameid":"2","title":"That Game","more stuff":"stuff 2"}]
,"3":[{"gameid":"3","title":"Another game","more stuff":"stuff 3"}]
}
我想我需要遍历每个数组获取我想要的值然后移动到下一个数组。我需要在不知道数组名称的情况下这样做,因为我不知道对象中有多少个数组。 感谢
答案 0 :(得分:0)
您可以在不知道其名称的情况下遍历json中的所有对象节点。以下使用杰克逊的例子:
public class Resolver {
public static List<String> getTitles(final String jsonString)
throws IOException {
List<String> result = new ArrayList<>();
ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree(jsonString);
Iterator<Map.Entry<String, JsonNode>> fields = json.fields();
while(fields.hasNext()){
Map.Entry<String, JsonNode> entry = fields.next();
System.out.println("|" + entry.getKey() + "| = entry.getKey()");
System.out.println("|" + entry.getValue() + "| = entry.getValue()");
result.add(entry.getValue().findPath("title").asText());
System.out.println("****************************");
}
return result;
}
}
测试类:
public class ResolverTest {
@Test
public void testGetTitles() throws Exception {
final String jsonString = "{"
+ "\"1\":[{\"gameid\":\"1\",\"title\":\"This Game\",\"more stuff\":\"stuff 1\"}]"
+ ",\"2\":[{\"gameid\":\"2\",\"title\":\"That Game\",\"more stuff\":\"stuff 2\"}]"
+ ",\"3\":[{\"gameid\":\"3\",\"title\":\"Another game\",\"more stuff\":\"stuff 3\"}]"
+ "}";
List<String> ids = Resolver.getTitles(jsonString);
System.out.println("|" + ids + "| = ids");
Assert.assertEquals(3, ids.size());
}
}
输出:
| 1 | = entry.getKey() | [{“gameid”:“1”,“title”:“This Game”,“more stuff”:“stuff 1”}] | = entry.getValue()
| 2 | = entry.getKey() | [{“gameid”:“2”,“title”:“那个游戏”,“更多东西”:“东西2”}] | = entry.getValue()
| 3 | = entry.getKey() | [{“gameid”:“3”,“title”:“另一个游戏”,“更多东西”:“东西3”}] | = entry.getValue()
| [这个游戏,那个游戏,另一个游戏] | = ids