Is there a way to convert a flat JSON into several instances of a sub-class through deserialization?

Here is a flat JSON string that needs to be deserialized in Java using Jackson:

{"ccy":"EUR", 
 "value1":500, 
 "value2":200, 
 "date":"2017-07-25", 
 "type":"", 
 ... <many other pairs>}

To deserialize this JSON string, we can create the following classes:

public class Data
{
  @JsonProperty("ccy")
  private String currency;

  private Amount value1;

  private Amount value2;

  @JsonProperty("date")
  private String date;

  @JsonProperty("type")
  private String type;

  ... <many other members>
}

public class Amount
{
  private double value;

  private String currency;

  public Amount(double value, String currency)
  {
    this.value = value;
    this.currency = currency;
  }
}

The challenge is how to correctly fill the value1 and value2 fields in the Data class. One approach is to use custom setters with Jackson annotations:

@JsonSetter("value1")
private void setValue1(double value1)
{
  this.value1 = new Amount(value1, this.currency);
}

@JsonSetter("value2")
private void setValue2(double value2)
{
  this.value2 = new Amount(value2, this.currency);
}

However, this solution relies on this.currency being deserialized first, which may not always be guaranteed.

Is there a more elegant solution that avoids using a custom constructor like

Data(@JsonProperty("value1") double value1, (@JsonProperty("value2") double value2, (@JsonProperty("ccy") String currency) {...}
?

Note: Using a solution that utilizes Jackson would be preferred.

Answer №1

If you're looking to utilize the GSON library, it provides a simple and effective solution. Let's say you have a Class named "User".

Gson gson = new Gson();
String jsonInString = "{\"userId\":\"1\",\"userName\":\"Yasir\"}";
User user= gson.fromJson(jsonInString, User.class);

To integrate this feature, you can include the following dependency:

<dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.6.2</version>
</dependency>

We hope this information proves helpful.

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

Combining duplicate keys in JSON aggregation using MySQL's many-to-many relationship

I'm facing a challenge with returning a JSON representation of a many-many join. My initial plan was to encode the columns returned in the following unique JSON format { "dog": [ "duke" ], "location": [ &quo ...

How to decode a JSON object in Golang that contains both trait and data?

I have a dictionary data structure containing words and their meanings in the format {{"word name":"word meaning"},{"word name":"word meaning"},...}. I am attempting to convert this into a map of the words, using the interface{} type. However, I am havin ...

Is it important to clean user input before displaying it on the screen while also permitting all characters

Currently, I have a JavaScript function that limits the characters accepted for user input in order to safely display it in the DOM. Now, I want to allow all characters while still encoding them to prevent any malicious scripts from executing. How can I a ...

Identify and enumerate the actionable components within a web page

I need assistance developing a Java function that can identify and return the count of interactive objects on a webpage that trigger an action when clicked, but excluding hyperlinks. Examples include buttons, image buttons, etc. Does anyone have any sugge ...

Developing J2EE servlets with Angular for HTTP POST requests

I've exhausted my search on Google and tried numerous PHP workarounds to no avail. My issue lies in attempting to send POST parameters to a j2ee servlet, as the parameters are not being received at the servlet. Strangely though, I can successfully rec ...

Tips for retrieving JSON data using Backbone.js

I'm experimenting with using backbones.js fetch to retrieve json from a twitter search and I need some help figuring out what's wrong with my code below. Can someone lend me a hand? (function($){ var Item = Backbone.Model.extend(); var Li ...

Is there a way to convert Firebase JSON into a JavaScript object? If so, what is the method to

I am currently working on using the kimono web scraper in conjunction with Firebase to obtain data stored as JSON. To convert the JSON to XML, I am utilizing a JavaScript library which allows me to create a variable from the JSON file (an example is shown ...

Java's UnreachableBrowserException in Selenium

System.setProperty("webdriver.chrome.driver","D:/chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.navigate().to("https://link"); driver.findElement(By.cssSelector("#username")).sendKeys("id"); driver.find ...

Error encountered in main thread: Illegal State Exception. The path to the driver executable needs to be defined using the webdriver.gecko.driver system

Despite trying various solutions from previous related issues, I have exhausted all options but continue to encounter the same error across FireFox, Chrome, and Internet Explorer. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; im ...

How to Transform JSON Element into a JavaScript Array in AngularJS?

Implementing AngularJS to fetch values in JSON format using $resource call. The model element I require is a Javascript array structured as: [ [1328983200000, 40], [1328983200000, 33], [1328983200000, 25], [1328983200000, 54], [1328983200000, 26], [1328 ...

Nested MongoDB object within multiple arrays

I need help with handling this JSON data structure: { data : { fields_data : [ [ { key1 : val }, { key1 : val } ], [ { key2 : val }, { key2 : val ...

How can you choose several keys at once from a JSON field using the ->> or #>> operators?

When working with the JSON field below: '{"firstname": "John", "secondname": "Smith", "age": 55}' Is there a way to select specific keys from the array, such as {"firstname", "seco ...

Converting an object with a System.Drawing.Image into a json format

I'm facing a bit of a challenge and struggling to find a solution... Within my interface (and implemented class), there is an image property... Guid uid { get; set; } Image imageData1 { get; set; } string fileName { get; set; } The imag ...

Generating JSON output in PHP

I've been struggling to figure out why I can extract some parts of the JSON data but not others... Essentially, I am retrieving JSON from a URL (). In my PHP code (using Laravel5), I have the following: $url = 'https://public-crest.eveonline.co ...

Managing JSON object with irregular data in Angular 7: Best Practices

When the service returns data in a specific format, I am able to view the data in the developer tools. {"results":{"BindGridDatatable":[{"ID":"0005","Name":"Rohit"}, {"ID":"0006","Name":"Rahul"}], "Totalvalue":119}} ...

How to effortlessly assign keys to values within a JSON object using Python

This is how my JSON data is structured: "docs": [ { "key": [ null, null, "some_name", "12345567", "test_name" ], "value": { ...

Refine JSON data by selecting only distinct key/value pairs

My JSON object has the following structure: var theSchools = { Bradley University: "bru", Knox College: "knox", Southern Illinois University Edwardsville: "siue",… } I am trying to find a way to retrieve the school name (key) based on the schoo ...

Is there a way to Clear All domain cookies using Selenium?

I am trying to figure out how to delete all cookies from all domains using Selenium WebDriver. Currently, Selenium only allows us to delete cookies from a specific domain. As an alternative solution, I attempted to use keypress events such as Ctrl+Shift+De ...

Decoding JSON with JavaScript following the response from JsonConvert.SerializeObject(json) in a .NET handler

I am currently working on a web application using the .NET platform. I have written a Handler code that returns a JSON object to JavaScript (after making an AJAX request). Here is the Handler code: var wrapper = new { left = left.ToString(), t ...

Saving a local JSON file in Angular 5 using Typescript

I am currently working on developing a local app for personal use, and I want to store all data locally in JSON format. I have created a Posts Interface and an array with the following data structure: this.p = [{ posts:{ id: 'hey man&ap ...