簡體   English   中英

在名稱不同於其getter的字段上使用jackson批注JsonUnwrapped

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM