Decode the implicit list in JSON format provided by the keys "1" and "2"

After retrieving this JSON data from an API, I need to convert it into a Java object. Here is the JSON structure:

{
    "message" : "message",
    "1": {
        "packageCode": "packageCode1",
        "packageNum": "packageNum1"
    },
    "2": {
        "packageCode": "packageCode2",
        "packageNum": "packageNum2"
    }
}

Is there a way to transform it into a Java object with the following attributes?

  • String message
  • Package [] packages

I am utilizing Jackson library for this conversion using ObjectMapper.

Appreciate your assistance!

Answer ā„–1

It would be more efficient to modify the API so that it returns an array of packages in the JSON response.

{
    "message" : "message",
    "packages": [
    {
        "packageCode": "packageCode1",
        "packageNum": "packageNum1"
    },
    {
        "packageCode": "packageCode2",
        "packageNum": "packageNum2"
    }]
}

If altering the API is not possible, you will need to create a custom deserializer by extending the StdDeserializer<T> class. This involves examining the JsonNode parse tree and constructing the desired object programmatically.

For guidance on this process, refer to this helpful article which includes a functional code example.

Answer ā„–2

I stumbled upon this effective solution that involves using a custom deserializer. I established a limit on the number of permissible packages, but you can opt to omit this check if it's not required.

Class Response:

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

    @Getter
    @Setter
    @ToString
    @JsonDeserialize(using = ResponseDeserializer.class)
    public class Response {
    
        private String message;
        private Package [] packages;
    }

Class Package:

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
public class Package {

    private String packageCode;
    private String packageNum;
}

Class ResponseDeserializer:

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

public class ResponseDeserializer extends StdDeserializer<Response> {

    private static final long serialVersionUID = -6665611685508708642L;
    private static final long MAX_PACKAGE_NUM = 1000;
    private ObjectMapper objectMapper = new ObjectMapper();

    public ResponseDeserializer() {
        this(null);
    }

    public ResponseDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public Response deserialize(JsonParser parser, DeserializationContext ctx)
            throws IOException {
        final JsonNode node = parser.getCodec().readTree(parser);
        final String message = node.get("message").asText();
        final List<Package> packageList = new ArrayList<>();
        for (var key = 1; key < MAX_PACKAGE_NUM; key++) {
            var packageNode = node.get(String.valueOf(key));
            if (null == packageNode) {
                break;
            }
            var currentPackage = objectMapper.treeToValue(packageNode, Package.class);
            packageList.add(currentPackage);
        }
        final var response = new Response();
        response.setMessage(message);
        response.setPackages(packageList.toArray(new Package[0]));
        return response;
    }
}

Class TestDeserializer (sample):

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TestDeserializer {

    public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
        String responseJSON = """
                                {
                    "message" : "message",
                    "1": {
                        "packageCode": "packageCode1",
                        "packageNum": "packageNum1"
                    },
                    "2": {
                        "packageCode": "packageCode2",
                        "packageNum": "packageNum2"
                    }
                }

                                """;
        Response response = new ObjectMapper().readValue(responseJSON, Response.class);
        System.out.println(response.toString());

    }
}

Answer ā„–3

Successfully resolved the issue using a custom deserializer.

package com.test.json;

import java.io.IOException;
import java.util.ArrayList;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

public class TestJsonObjectDeserializer extends StdDeserializer<TestJsonObject> {

    private static final long serialVersionUID = 1L;

    public TestJsonObjectDeserializer() {
        this(null);
    }

    protected TestJsonObjectDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public TestJsonObject deserialize(JsonParser jsonParser, DeserializationContext arg1) throws IOException, JsonProcessingException {
        TestJsonObject testJsonObject = new TestJsonObject();
        JsonNode jsonNode = jsonParser.getCodec().readTree(jsonParser);
        String message = jsonNode.get("message").textValue();
        ArrayList<Package> packages = new ArrayList<Package>();
        if (message != null) {
            testJsonObject.setMessage(message);
            int i = 1;
            Package package1 = null;
            do {
                package1 = null;
                JsonNode pkg = null;
                if (jsonNode.get(String.valueOf(i)) != null) {
                    pkg = jsonNode.get(String.valueOf(i));
                    String packageCode = pkg.get("packageCode").textValue();
                    String packageNum = pkg.get("packageNum").textValue();
                    package1 = new Package();
                    package1.setPackageCode(packageCode);
                    package1.setPackageNum(packageNum);
                }
                i++;
                if (package1 != null) {
                    packages.add(package1);
                }
            } while (package1 != null);

            if (!packages.isEmpty()) {
                Package[] packages1 = new Package[packages.size()];
                testJsonObject.setPackages(packages.toArray(packages1));
            }
            return testJsonObject;
        }
        return null;
    }

}

The following are the object classes: Package.java

package com.test.json;

public class Package {
    protected String packageCode;
    protected String packageNum;

    public String getPackageCode() {
        return packageCode;
    }

    public void setPackageCode(String packageCode) {
        this.packageCode = packageCode;
    }

    public String getPackageNum() {
        return packageNum;
    }

    public void setPackageNum(String packageNum) {
        this.packageNum = packageNum;
    }

    @Override
    public String toString() {
        return "Package [packageCode=" + packageCode + ", packageNum=" + packageNum + "]";
    }
}

TestJsonObject:

package com.test.json;

import java.util.Arrays;

public class TestJsonObject {
    protected String message;
    protected Package[] packages;

    public String getMessage() {
        return message;
    }

    @Override
    public String toString() {
        return "TestJsonObject [message=" + message + ", packages=" + Arrays.toString(packages) + "]";
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Package[] getPackages() {
        return packages;
    }

    public void setPackages(Package[] packages) {
        this.packages = packages;
    }
}

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

retrieving values from a JSON array in Xcode

Just starting out with XCODE and Objective C, I've been searching through forums but can't find what I need. I'm attempting to extract a specific value from an array using Teleduino web service. However, for some reason, I'm not getting ...

The server is unable to receive lists that are included within the JSON object being passed in

Below are the data contracts utilized in the function. public class ResumeSkillsListDataContract : IResumeSkillsListDataContract { public IList<ISkillDataContract> KnownSkillsList { get; set; } public IList<ISkillDataContract> BadSkill ...

employing a robotic tool to download a webpage under various file names

I am currently utilizing selenium to develop a robot that automates the process of opening and saving a webpage. Here is the code snippet: WebDriver driver = new FirefoxDriver(); driver.get("http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber= ...

Leveraging DataProvider in TestNG with a single instantiation of WebDriver

Trying to validate the login page control using a data provider without reinitializing the webdriver for each username and password input. I want to check all relevant scenarios on the login page at once without restarting another driver. However, I'm ...

Searching for the perfect way to choose 'mat-checkbox' using the selenium webdriver?

There are 4 checkboxes that I need to select using Angular code and Selenium for automation. Please refer to the provided code for assistance. I specifically need to select the checkbox labeled "Main st & 19th St". View image description here ...

Using Python to Transform Nested JSON Data into an Unordered List in HTML

After conducting thorough research on Google, I was unable to find a suitable solution for converting arbitrarily nested JSON data into an unordered list format using HTML and Python. Ultimately, the problem was resolved with the help of a concise recursi ...

Having trouble receiving the desired JSON format with xml2js, is there a way to resolve this issue?

After attempting to convert an XML file obtained from an external server into JSON using xml2json, it appears that the conversion is not producing a valid JSON output. It seems like there may be an issue with missing quotes for the keys. Are there adjustme ...

Efficiently loading data using lazy loading in jsTree

I have been facing a challenge with dynamically loading the nodes of a jtree upon expansion. The limited documentation I could find is located towards the end of this specific page. Several solutions involve creating nodes individually using a loop, simil ...

Vega-Lite: Comet chart trails glide across both axes instead of just moving horizontally as intended

I'm currently working on visualizing electoral data from Malaysia using Vega-Lite. The dataset I'm using includes information about the seats won by each political party in each state during both the 14th and 15th elections. You can access the da ...

Having trouble making JSON work alongside Ajax and jQuery?

In my JavaScript, I have the following code snippet... $.ajax({ type: 'POST', url: 'http://www.example.com/ajax', data: {email: val}, success: function(response) { alert(response); } }); The PHP fil ...

Reduce JSON for efficient deserialization and persistence of intricate POJOs using JPA/Hibernate

Dealing with deserialization of a complex POJO from a JSON string and persisting it in a MySQL database can be quite challenging. Below is a simplified example class: @Entity @Table(name="a") public class A{ private Long id; private B b; priva ...

Send a request to the XML file through the web

I am currently working with a vendor who has provided me with information that I need to code in order to retrieve data from them. The task at hand is sending a POST request to a URL that ends with .xml. The documentation specifies that the request shoul ...

Which method is considered more RESTful: creating a resource with a JSON payload or using regular POST parameters?

As I develop an API, I ponder whether to implement a factory endpoint that accepts a JSON payload with the resource attributes to be created, utilize regular application/x-www-form-urlencoded parameters in the request body, or if it's inconsequential ...

Seeking information from JSON data using an internet address

Currently, I am utilizing the following URL to access my JSON data: myapp/laravelRoute/jsondata By entering this in the address bar, the JSON array below will be shown: [{"A":"B"},{"B":1},{"C","http"}] However, when I input the URL as follows: myapp/l ...

Access the data within the nested JSON object

As I attempt to retrieve a value from a deeply nested Json object, I encounter a Parse error: The Json data I'm working with: { "MessageId": "f6774927-37cf-4608-b985-14a7d86a38f9", "Time": "2017-04-06T16:28: ...

Tips on utilizing json.tool in the command line to validate and format language files while preserving unicode characters

Ubuntu 16.04 Bash 4.4 python 3.5 After receiving a collection of language files from freelance translators on Upwork, it became evident that none of the files had matching line counts. To address this discrepancy, I decided to validate and format the ...

Exploring the inner workings of a JSON with Ajax and PHP

I'm working on a project that involves a JSON file called items.json. My goal is to create a search box where users can input either the name of an item or its category, and see live search results as they type. Here's what Iā€™m aiming for: If ...

What is the best method for transferring updated data from the frontend to the backend without needing to store any unchanged values?

After importing a list from a database using axios and storing it in a variable called tasks, each object may resemble the following structure: tasks: [ { title: 'some text here' }, { completed: false }, ] If there are 2000 or 3000 of ...

Could it be possible that my code is preventing any duplicate entries in a table?

Currently, I am in the process of developing an application that utilizes JSON data which is regularly updated with fresh JSON data from a Delphi application that I am concurrently working on. Below is the stored procedure I have created to import this inf ...

Error Alert: String indices must be integers. This message continues to appear, indicating a recurring issue. What could possibly be causing this error?

Every time I encounter a TypeError saying "string indices must be integers." What could be causing this issue? IMG_DIR = 'default/*.png' JSON = 'annotations/default.json' Type: \<class 'dict'\> {'info&apo ...