您可以使用 Jackson DataBind API 来获取所有 Key、Value 对。
String json = "{\"Id\":\"1223-SHD5-33FA-29T7\",\"Properties\":[{\"someProperty\":\"someValue\",\"anotherPropertry\":\"anotherValue\",\"subProperty\":{\"IP\":[\"113.73.47.114\",\"144.156.146.219\",\"153.103.248.24\"]},\"oneMoreProperty\":[\"someOtherValue\"]}]}";
ObjectMapper om = new ObjectMapper();
JsonNode jsonNode = om.readTree(json);
for (Map.Entry<String, JsonNode> elt : jsonNode.fields())
{
//get keys and values
}
您可以使用 Jay-Way API 来获取基于路径的值。您还可以使用正则表达式来获取所需的值。
String json = "{\"Id\":\"1223-SHD5-33FA-29T7\",\"Properties\":[{\"someProperty\":\"someValue\",\"anotherPropertry\":\"anotherValue\",\"subProperty\":{\"IP\":[\"113.73.47.114\",\"144.156.146.219\",\"153.103.248.24\"]},\"oneMoreProperty\":[\"someOtherValue\"]}]}";
ReadContext ctx = JsonPath.parse(json);
String id = ctx.read("$.Id");
String someProperty = ctx.read("$.Properties[0].someProperty");
System.out.println(id);
System.out.println(someProperty);
您可以使用下面的方式获取依赖项
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
使用 Jay-Way,您无需在每次查找键值时都遍历整个树。