简体   繁体   中英

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:

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

I want to get title value.

I try

testToJson.get("title")

but it returns null.

How to get title value with jackson?

You can deserialise it to a JsonNode and use JSON Pointer to get required field:

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.

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.

Jackson captures the data about generics using a sub-classed instance of TypeReference<T> .

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. 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. 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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