简体   繁体   English

如何使用 jackson 获得 json 值?

[英]How to get json value with jackson?

String url = "https://ko.wikipedia.org/w/api.php?action=query&format=json&list=search&srprop=sectiontitle&srlimit=1&srsearch=grand-theft-auto-v";

String test = restTemplate.getForObject(url, String.class);

Map<String, String> testToJson = objectMapper.readValue(test, Map.class);

testToJson is: testToJson是:

{
    batchcomplete: "",
    continue: {
        sroffset: 1,
        continue: "-||",
    },
    query: {
        searchinfo: {
            totalhits: 12
        },
        search: [
            {
                ns: 0,
                title: "그랜드 테프트 오토 V",
                pageid: 797633,
            }
        ],
    },
}

I want to get title value.我想获得title值。

I try我试试

testToJson.get("title")

but it returns null.但它返回 null。

How to get title value with jackson?如何使用 jackson 获取title值?

You can deserialise it to a JsonNode and use JSON Pointer to get required field:您可以将其反序列化为JsonNode并使用JSON Pointer获取必填字段:

JsonNode node = mapper.readValue(jsonFile, JsonNode.class);
String title = node.at("/query/search/0/title").asText();

you could build a class for this json result then read from it.您可以为此 json 结果构建 class 然后从中读取。

public class Result {
  private JsonNode searchinfo;
  private JsonNode[] searches;
}
// then read:
Result testToJson = objectMapper.readValue(test, Result.class);
System.out.println(testToJson.getSearches(0).get("title"));

refer参考

It is impossible to read JSON into an instance of a generic class like that because the info about generics are used in compile time and already lost when program is running.不可能像这样将 JSON 读入通用 class 的实例,因为有关 generics 的信息在编译时使用并且在程序运行时已经丢失。

Jackson captures the data about generics using a sub-classed instance of TypeReference<T> . Jackson 使用TypeReference<T>的子类实例捕获有关 generics 的数据。

Map<String, String> testToJson = objectMapper.readValue(test, new TypeReference<Map<String, String>>(){});

The problem with this approach is that Map<String, String> almost never describes complex data (like in the example) correctly.这种方法的问题是Map<String, String>几乎从不正确描述复杂数据(如示例中所示)。 The example contains not only string values, there are numbers and even nested objects.该示例不仅包含字符串值,还包含数字甚至嵌套对象。

In situations like that, when you don't want or cannot write a class that describes the structure of the JSON, the better choice is parsing the JSON into a tree structure and traverse it.在这种情况下,当您不想或不能编写描述 JSON 结构的 class 时,更好的选择是将 JSON 解析为树结构并遍历它。 For example:例如:

JsonNode node = objectMapper.readTree(test);
String title = node.get("query").get("search").get(0).get("title").asText();
Integer offset = node.get("continue").get("strOffset").asInt()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM