Is it possible to deserialize this Json to the specified Java Dto using Jackson ObjectMapper without the need for a custom @JsonCreator?

I have created two Java classes named Request and Item:

public class Request
{
    private List<Item> subItems;

    public Request()
    {
    }

    public List<Item> getSubItems()
    {
        return subItems;
    }

    public void setSubItems(List<Item> subItems)
    {
        this.subItems = subItems;
    }
}

class Item
{
    private String name;
    private String functionName;

    //...elided...
}

In my scenario, the subItems passed can either be complex (including a function) or simple (just a name), or a mix of both types. To make it easier to handle JSON data, I want to receive input in the following format:

JSON:

{
  "subItems": [
    {
      "name": "complexType",
      "function": "someFunction"
    },
    "simpleType"
  ]
}

After receiving this JSON, I expect it to be converted into instances similar to the ones below:

Request request = new Request();
request.setSubItems(
    Arrays.asList(
        new Item( "complexType", "SomeFunction" ),
        new Item( "simpleType" )
    )
);

My question is: Can Jackson/ObjectMapper handle this conversion? What configurations and annotations would be required?

Answer №1

When the constructor of your Item class contains a string parameter, it will be invoked with the value "simpleType".

class Item {
    private String name;
    private String functionName;

    public Item() {
    }

    public Item(String name) {
        this.name = name;
    }

    // getters and setters here
}

Demonstration in full

public class Request {
    public static void main(String[] args) throws IOException {
        String json = "{\"subItems\":[" +
                          "{\"name\":\"complexType\",\"functionName\":\"SomeFunction\"}," +
                          "\"simpleType\"" +
                      "]}";
        Request request = new ObjectMapper().readValue(json, Request.class);
        System.out.println(request);
    }

    private List<Item> subItems;
    public Request() {
    }
    public Request(Item... subItems) {
        this.subItems = Arrays.asList(subItems);
    }
    public List<Item> getSubItems() {
        return this.subItems;
    }
    public void setSubItems(List<Item> subItems) {
        this.subItems = subItems;
    }
    @Override
    public String toString() {
        return "Request [subItems=" + this.subItems + "]";
    }
}
class Item {
    private String name;
    private String functionName;
    public Item() {
    }
    public Item(String name) {
        this.name = name;
    }
    public Item(String name, String functionName) {
        this.name = name;
        this.functionName = functionName;
    }
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getFunctionName() {
        return this.functionName;
    }
    public void setFunctionName(String functionName) {
        this.functionName = functionName;
    }
    @Override
    public String toString() {
        return "Item [name=" + this.name + ", functionName=" + this.functionName + "]";
    }
}

Result

Request [subItems=[Item [name=complexType, functionName=SomeFunction], Item [name=simpleType, functionName=null]]]

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

Navigating a JSON object with Coffeescript iteratively

I'm a beginner in Coffeescript and I'm facing a challenge with resolving an issue. Currently, I have a JSON object stored in a variable. Can somebody guide me on how to loop through the keys in the JSON object to show both the key name and its co ...

What is the method for inputting multi-line strings in the REST Client extension for Visual Studio Code?

Clarification There seems to be some confusion regarding the nature of the data I am storing. I am developing a code snippet web application using Express.js and MongoDB. The purpose is not to store executable code for later use; instead, I am saving snipp ...

Working with Linq in JSON Serialization

Below is a json string that I have: { 'Sheet1': [{ 'EmployeeNo': '123456', 'EmployeeName': 'Midhun Mathew' }, { 'EmployeeNo': '123457& ...

OutOfMemoryError caused by Bitmap

I'm experiencing an issue with this error. I created a favicon parser from URLs using the following code: public class FavIconParser { public static String extractUrl(String url) { StringBuffer sb = new StringBuffer(); Pattern p = Pattern.co ...

Access the value of a JSON property, return null if the key is not found, all in one line of JavaScript code

How about a fun analogy in Python: fruits_dict = {"banana": 4, "apple": 3} num_apples = fruits_dict.get("apple", None) num_oranges = fruits_dict.get("orange", None) print(num_apples, num_oranges) The result would be: 3 None If we switch gears to Jav ...

Is there a way to load JSON data into an OrderedDict structure?

Is it possible to use an OrderedDict as an output in json.dump? I know it can be used as an input, but I'm curious about maintaining key order when loading into an OrderedDict. If it's not directly possible, are there any alternative solutions o ...

Understanding JSON in R by extracting keys and values

I have a JSON URL that I need to parse in R. The URL is https://{{API_HOST}}/api/dd/new and contains both keys and values. I can easily parse this JSON in Postman by using the keys and values in the Headers section. Now, I am looking for a way to achieve t ...

What is the best way to sort my API responses to display only users who are either currently online or offline?

Hi everyone, I've made great progress on my project so far without any assistance (pretty proud of myself), but now I could use some help. I'm working on creating a tabbed menu that filters the results of my API calls to display: All users, Onlin ...

Is it better to DeepCopy the List<T> instead of instantiating new instances from JSON?

Having a List of objects such as List<Employee>, each employee in the list is loaded from a .JSON file. I also need to generate new instances based on List<Employee> and only modify the properties of the new instance for the new employee creati ...

Exploring collapsible data tables in Angular with Bootstrap styling

I am attempting to transform my static bootstrap data table, which displays the total count of fruits harvested in various months in an incremental manner, into a dynamic one using the JSON provided below: JSON { "fruit": [ { "fruitName": "Al ...

Exploring Data within Data Structures

I am currently making two JSON requests in my code: d3.json("path/to/file1.json", function(error, json) { d3.json("path/to/file2.json", function(error, json2) { }); }); The structure of json 2 looks like this: [ { "city" : "LA", "locati ...

Transmit a JSON payload to the Codeigniter controller

I encountered an issue where my JSON data was not being properly sent to the controller. Despite checking the XHR and confirming that the post data was not empty, the controller was receiving an empty array. In my view: $.ajax({ type : "POST", url ...

The concept of undefined does not hold any tangible form

TypeError: undefined is not an object (evaluating 'this.props.data.map') appContent: displayData(){ let info = this.props.data.map(function(dataItem, index) { return ( <Card> <CardItem> <Body ...

What is the best way to retrieve a response from a PHP file as an array through Ajax?

Seeking assistance in retrieving a complete address by entering the postal code in an HTML form textbox and clicking a button. The setup involves two files - one containing the ajax function and the other housing the PHP code. Uncertainty looms over whethe ...

javax.el.MethodNotFoundException: JSP method cannot be located

While compiling the JSP template, I encountered the following exception: The method getFriendImage() is not recognized I attempted to rebuild the class without success. The src attribute contains a valid link to an image that is functioning properly. ...

Should servlet response be HTML for use in AJAX calls?

I am currently in the process of developing a web application with multiple pages, including index.html which serves as the main page and contains various <a> tabs linking to different Servlet pages. As part of my design, I have a consistent CSS lay ...

What could be causing the data retrieved from the JSON action to appear as "undefined"?

Have you examined the console.log() outputs and table structure for correctness? I suspect an error in one of them. I am fetching data from the database and using console.log() to display both the data in the loadData() function and value in the $.each(). ...

A step-by-step guide on retrieving JSON information and saving it as a CSV file

Click here for JSON data on COVID-19 mobility trends. Here is a snippet of the JSON data: { "data": { "Albania": [ { "name": "driving", "title": "driving", "values": [ { "date": "2020-01-13", "value": "100" }, { "date": "2020-01-14", "value": "95.3" }, { ...

How can I manage excessive amounts of data in a single line and prevent overwhelming the system?

The title may be a bit confusing, but what I am trying to convey is: InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; JSONArray ja = new JSONArray(); wh ...

Connecting to an Oracle database using Alfresco's Javascript API may seem daunting at first, but

Currently, I am working on a project that involves using Alfresco. One of the new requirements for this project is to retrieve a sequence number from our Oracle database and populate a custom property within an Alfresco space. var conObj = new ActiveXObje ...