[英]Use jackson annotation JsonUnwrapped on a field with name different from its getter
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 我想使用具有以下结构的Jackson将Car对象转换为JSON
'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 我已经尝试过在此提供的答案,但是它对我不起作用,因为字段名称不同于getter
I know I can use @JsonUnwrapped on engine if field name was engine. 我知道如果字段名称是engine,我可以在engine上使用@JsonUnwrapped。 But how to do in this situation.
但是在这种情况下该怎么办。
provide @JsonUnwrapped
and @JsonProperty
together: 一起提供
@JsonUnwrapped
和@JsonProperty
:
@JsonUnwrapped
@JsonProperty("engine")
private Engine myEngine;
You shall use the @JsonUnwrapped
as follows in the Car class for the desired JSON object: 您应在Car类中按如下方式使用
@JsonUnwrapped
作为所需的JSON对象:
class Car {
@JsonUnwrapped
private Engine myEngine;
@JsonProperty("color")
private String myColor;
@JsonProperty("maxspeed")
private int myMaxspeed;
...
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. 我认为最好的解决方案是在
Engine
类的myEngineType
属性上使用@JsonValue
批注,它只会序列化此属性,而不是整个Engine
对象。
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. 您可以查看此答案以获取更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.