问题
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.
回答1:
provide @JsonUnwrapped
and @JsonProperty
together:
@JsonUnwrapped
@JsonProperty("engine")
private Engine myEngine;
回答2:
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;
...
回答3:
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.
来源:https://stackoverflow.com/questions/46109599/use-jackson-annotation-jsonunwrapped-on-a-field-with-name-different-from-its-get