![](/img/trans.png)
[英]Jackson: "Can not set final" when deserializing Java record with @JsonUnwrapped annotation
[英]Use jackson annotation JsonUnwrapped on a field with name different from its getter
我有一個像這樣的課程:
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;
}
}
和引擎類
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;
}
}
我想使用具有以下結構的Jackson將Car對象轉換為JSON
'car': {
'color': 'red',
'maxspeed': '200',
'fueltype': 'diesel',
'enginetype': 'four-stroke'
}
我已經嘗試過在此提供的答案,但是它對我不起作用,因為字段名稱不同於getter
我知道如果字段名稱是engine,我可以在engine上使用@JsonUnwrapped。 但是在這種情況下該怎么辦。
一起提供@JsonUnwrapped
和@JsonProperty
:
@JsonUnwrapped
@JsonProperty("engine")
private Engine myEngine;
您應在Car類中按如下方式使用@JsonUnwrapped
作為所需的JSON對象:
class Car {
@JsonUnwrapped
private Engine myEngine;
@JsonProperty("color")
private String myColor;
@JsonProperty("maxspeed")
private int myMaxspeed;
...
我認為最好的解決方案是在Engine
類的myEngineType
屬性上使用@JsonValue
批注,它只會序列化此屬性,而不是整個Engine
對象。
因此,您的代碼將如下所示:
class Engine {
@JsonProperty("fueltype")
private String myFueltype;
@JsonValue
@JsonProperty("enginetype")
private String myEnginetype;
}
您可以查看此答案以獲取更多詳細信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.