本文介绍了在名称不同于其getter的字段上使用jackson批注JsonUnwrapped的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的课程:

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;
    }
}

和类似的引擎类

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

I want to convert the Car object to JSON using Jackson with structure like

'car': {
   'color': 'red',
   'maxspeed': '200',
   'fueltype': 'diesel',
   'enginetype': 'four-stroke'
 } 

我尝试了中提供的答案但这对我不起作用,因为字段名称不同于getter

I have tried answer provided in this but it doesn't work for me as field names are different then getter

我知道如果字段名称是engine,我可以在engine上使用@JsonUnwrapped.但是在这种情况下该怎么办.

I know I can use @JsonUnwrapped on engine if field name was engine. But how to do in this situation.

推荐答案

一起提供@JsonUnwrapped@JsonProperty:

@JsonUnwrapped
@JsonProperty("engine")
private Engine myEngine;

这篇关于在名称不同于其getter的字段上使用jackson批注JsonUnwrapped的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 13:58