Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jackson annotation JsonUnwrapped on a field with name different from its getter

Tags:

java

json

jackson

I have a class like:

class Car {
    private Engine myEngine;

    @JsonProperty("color")
    private String myColor;  

    @JsonProperty("maxspeed")
    private int myMaxspeed;

    @JsonGetter("color")
    public String getColor()
    {
        return myColor;
    }

    @JsonGetter("maxspeed")
    public String getMaxspeed()
    {
        return myMaxspeed;
    }

    public Engine getEngine()
    {
        return myEngine;
    }
}

and Engine class like

class Engine {
    @JsonProperty("fueltype")
    private String myFueltype;

    @JsonProperty("enginetype")
    private String myEnginetype;

    @JsonGetter("fueltype")
    public String getFueltype()
    {
        return myFueltype;
    }

    @JsonGetter("enginetype")
    public String getEnginetype()
    {
        return myEnginetype;
    }
}

I want to convert the Car object to JSON using Jackson with structure like

'car': {
   'color': 'red',
   'maxspeed': '200',
   'fueltype': 'diesel',
   'enginetype': 'four-stroke'
 } 

I have tried answer provided in this but it doesn't work for me as field names are different then getter

I know I can use @JsonUnwrapped on engine if field name was engine. But how to do in this situation.

like image 954
learner Avatar asked Sep 08 '17 05:09

learner


1 Answers

provide @JsonUnwrapped and @JsonProperty together:

@JsonUnwrapped
@JsonProperty("engine")
private Engine myEngine;
like image 94
Sachin Gupta Avatar answered Sep 18 '22 16:09

Sachin Gupta