java - How do I deserialize flat JSON into multiple instances of a sub-class? -


i got flat json string like

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

the json string shall deserialized in java using jackson:

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> } 

with

public class amount {   private double value;    private string currency;    public amount(double value, string currency)   {     this.value = value;     this.currency = currency;   } } 

what correct use of jackson annotations fill value1 , value2 fields in data class?

i tried custom setters like:

@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); } 

but works if this.currency deserialized first (what cannot rely on).

is there neat solution not use custom constructor data(@jsonproperty("value1") double value1, (@jsonproperty("value2") double value2, (@jsonproperty("ccy") string currency) {...} ?

edit: approach uses jackson preferred.

you can use gson library.
it's easy approach. assume class "user"

gson gson = new gson(); string jsoninstring = "{\"userid\":\"1\",\"username\":\"yasir\"}"; user user= gson.fromjson(jsoninstring, user.class); 

add using dependency

<dependency>         <groupid>com.google.code.gson</groupid>         <artifactid>gson</artifactid>         <version>2.6.2</version> </dependency> 

hope helps


Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -