8

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.

learner
  • 1,952
  • 7
  • 33
  • 62

3 Answers3

12

provide @JsonUnwrapped and @JsonProperty together:

@JsonUnwrapped
@JsonProperty("engine")
private Engine myEngine;
Sachin Gupta
  • 7,805
  • 4
  • 30
  • 45
0

You shall use the @JsonUnwrapped as follows in the Car class for the desired JSON object:

class Car {

    @JsonUnwrapped
    private Engine myEngine;

    @JsonProperty("color")
    private String myColor;  

    @JsonProperty("maxspeed")
    private int myMaxspeed;
    ...
Naman
  • 27,789
  • 26
  • 218
  • 353
0

I think the best solution here would be to use @JsonValue annotation over the myEngineType attribute in your Engine class, it will only serialize this attribute instead of the whole Engine object.

So your code would be like this:

class Engine {

    @JsonProperty("fueltype")
    private String myFueltype;

    @JsonValue
    @JsonProperty("enginetype")
    private String myEnginetype;

}

You can take a look at this answer for more details.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78