名前を知らずに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;
}
}
Testクラス:
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": "このゲーム"、 "more stuff": "stuff 1"}] | = entry.getValue()
2 | = entry.getKey() [{"gameid": "2"、 "title": "そのゲーム"、 "more stuff": "stuff 2"}] | = entry.getValue()
| 3 | = entry.getKey() [{"gameid": "3"、 "title": "もう一つのゲーム"、 "more stuff": "stuff 3"}] | = entry.getValue()
[このゲーム、そのゲーム、別のゲーム] | = ids
あなたはGsonのようなjsonライブラリを試しましたか? https://github.com/google/gson – Scott