Jackson: A Guide to Extracting JSON Values

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 result = restTemplate.getForObject(url, String.class);

Map<String, String> jsonResult = objectMapper.readValue(result, Map.class);

The value of jsonResult is:

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

I am trying to retrieve the value of title.

This is what I have tried:

jsonResult.get("title")

However, it returns null.

Is there a way to extract the value of title using jackson?

Answer №1

One approach to extracting a specific field from a JSON file is by deserializing it into a JsonNode object and utilizing the power of JSON Pointer:

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

Answer №2

One way to handle the returned JSON result is by creating a custom class for it and parsing the data accordingly.

class SearchResult:
    def __init__(self, search_info, searches):
        self.search_info = search_info
        self.searches = searches

# Parsing the JSON result
result_json = json.loads(result)
search_result = SearchResult(result_json['searchinfo'], result_json['searches'])

# Accessing specific data from the parsed result
print(search_result.searches[0]['title'])

You can find more information about mapping dynamic objects using Jackson here.

Answer №3

Reading JSON into a generic class instance in this way is not possible due to the loss of generics information during runtime.

Jackson overcomes this limitation by using an sub-classed instance of TypeReference<T> to capture the generics data.

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

The issue with this approach is that Map<String, String> may not accurately represent complex data structures, as seen in the provided example. The example includes not only string values but also numbers and nested objects.

In cases where it's not feasible or desired to create a dedicated class to describe the JSON structure, a better alternative is to parse the JSON into a tree structure and navigate it accordingly. For example:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting multiple lists to JSON in Python: A comprehensive guide

There are 4 lists with unique identifiers. The data on lists Spec_titles, spec_details, and varients is being cleared over a loop and new details are appended onto them. name=["Some_car1","Some_car2",..."Some_carx"] spec_titles=["price", "engine", "bhp", ...

Is there a way to verify if a checkbox has been checked?

Having trouble with this code: if($('#primayins').prop('checked')) { $("#tx_nm0x0_pricingplan").val(1); } else { $("#tx_nm0x0_pricingplan").val(2); } It keeps returning false consistently ...

Query to retrieve all IDs contained within the list stored in TinyDB

In my python project, I am utilizing TinyDB to enhance the logic. To improve efficiency, I need to be able to retrieve multiple objects in a single query, preferably using a list. listOfIDs = ['123', '456'] I am working with the lates ...

Parsing JSON with NewtonSoft JsonConvert

I encountered this error while trying to deserialize JSON text: Unexpected character encountered while parsing value: {. Path '[0]', line 1, position 3. The JSON Text was validated on JSONLint.com and here is the JSON text: [ [ {"t ...

Difficulty Encountered when Combining Selenium Page Object Pattern and WebDriverWait

I implemented a Selenium page object in my recent project and utilized WebDriverWait to ensure the element is loaded before interacting with it. @FindBy(how = How.ID, using = "username") private WebElement username; @FindBy(h ...

"Python's ability to dynamically update and print multiple lines in real-time

As a newcomer to Python, I am faced with a challenge that I cannot seem to crack. My Objective: I am seeking a method to dynamically update and display output on multiple lines within the console. While there are numerous solutions available for single-l ...

Extracting JSON data and populating an ArrayList with the results

Receiving a JSON response is not the issue The challenge lies in extracting data from the response and populating an arraylist with specific fields Here is what I have attempted so far : protected String doInBackground(String... args) { fr ...

Convert Java object to JSON format compatible with D3's circle packing visualization

I have a unique data structure in Java that resembles the following public class Folder { private Map<String, Folder> directories = new HashMap<>(); private Map<String, GitFile> files = new HashMap<>(); private String n ...

Displaying JSON data in a popup window resembling a download prompt

I'm a beginner in front end development and facing difficulty in displaying JSON in a new window. Currently, I'm allowing users to download the JSON file like this var blob = new Blob([$scope.data], {type: 'json'}); ...

Using JSON in Android to Load Data and Display in a ListView

I've encountered an issue with the following code that is meant to read a JSON file and display it in a listview - it's returning an empty list. Any advice would be greatly appreciated. Thanks! eventList.json: { "events": [ { "event": "Taste o ...

Having Trouble with Sending Emails Using Google Scripts - Javascript POST Request Issue

I have been working on setting up a basic form on my website where users can input their name, email, and a short message. This information is then sent to Google Apps Script which forwards the message to me via email. Unfortunately, I keep encountering an ...

"Assertj is used to compare the extracted values, specifically when they are arrays

My situation involves requesting sets of names from two different systems and checking if they are equal, regardless of the order. The code below seems to work fine: assertThat(asList(assertThat(firstJSON) .flatExtracting("innerObject") .extractin ...

Python - JSON TypeError: the given key 'tuple' is not a string

I have a collection of data in the form of a dictionary. The keys in this dictionary are tuples: data = {'example': {('key1', 1): 1, ('key2', 2): 1, ('key3', 3): 1}} My goal is to save this data in JSON format by w ...

A JSON object containing a PHP variable

I'm trying to integrate a PHP variable into my PayPal single payout call code where the price is defined at 'value':".$planPrice." When I manually input a number like "1000", it works fine and I receive the notification. However, when I use ...

I'm experiencing some strange symbols on my page that look like ''. It appears to be a problem occurring between the servlet and the Javascript. How can I resolve this issue?

After retrieving a CSV file from my servlet, I noticed that characters like 'é', 'á' or 'õ' are not displaying properly on my page. Strangely, when I access the servlet directly via browser, everything appears fine. I atte ...

Convert JSON into a class with the 'paste special' feature is not available in Visual Studio 2019, even though all web

One useful feature is the ability to easily extract JSON and generate a class from it. In previous versions of VS, Paste Special was a handy tool, but I can't seem to find it in Visual Studio 2019. After checking out this forum thread, it seems addin ...

Tips for updating a single key within a JSON file using node.js

I'm in the process of creating an API for my Minecraft server and I've managed to successfully update a JSON file with the data from a POST request. Is there a way to selectively update only one key in the JSON file? Here's the code snippet ...

Decoding JSON for RESTful API communication

After parsing the following json string to a REST api, I noticed that only the first entry was being printed out with a printline statement. How can I modify this code to display the expected results? json input { "age": "10", "name": "Daniel" }, ...

The Content property of the HttpRequestMessage is populated with characters that are invalid and cannot be

After receiving the return from HttpRequestMessage.Contenc, it appears to be encrypted. Has anyone else experienced something similar? var client2 = new HttpClient(); client2.DefaultRequestHeaders.Accept.Clear(); client2.DefaultReq ...

Retrieve the radio button value without using a key when submitting a form in JSON

Looking to extract the value upon form submission in Angular, here is the code: In my Typescript: constructor(public navCtrl: NavController, public navParams: NavParams, public modalCtrl: ModalController, public formBuilder: FormBuilder, public alertCtrl ...