如何将JSON字段名称映射到不同的对象字段名称?

Ble*_*eek 37 java xml json annotations jackson

对于以下jax-b注释,Jackson json注释中的等价方式是什么?

我需要生成json而不是xml,并且需要知道在jax-b中等效表示的传统jackson注释.

  1. 重命名一个字段.
  2. 使用getter而不是字段.

如果json/xml元素名称是一个java保留字,如" new"," public"," static"等,这些功能尤其重要.

因此,我们必须将POJO字段分别命名为"_new_","_ public _","_ static_"等,

但是使用jax-b注释将它们重命名为生成的XML(和json)元素中的"new","public","static"等.

重命名字段

@XmlAccessorType(XmlAccessType.FIELD)
public class Person{
    @XmlElement(required = true)
    protected String name;
    @XmlElement(required = true)
    protected String address;
    @XmlElement(name = "contractor")
    protected boolean _restricted_ ;
    @XmlElement(name = "new")
    protected boolean _new_ ;
}
Run Code Online (Sandbox Code Playgroud)

重定向到使用属性getter(我认为这是在jax-b中完成的方式)

@XmlAccessorType(XmlAccessType.PROPERTY)
public class Person{
    protected String name;
    protected String address;
    protected boolean _restricted_ ;
    protected boolean _new_ ;

    @XmlElement(required = true)
    protected String getName() {return name;}
    @XmlElement(required = true)
    protected String getAddress() {return address;}
    @XmlElement(name = "contractor")
    protected boolean getRestricted() {return _restricted_;}
    @XmlElement(name = "new")
    protected boolean getNew(){return _new_;}
}
Run Code Online (Sandbox Code Playgroud)

Enr*_*man 88

可能它有点晚了但无论如何..

您可以重命名只添加的属性

@JsonProperty("contractor")
Run Code Online (Sandbox Code Playgroud)

默认情况下,Jackson使用getter和setter来序列化和反序列化.

有关更多详细信息,请访问:http://wiki.fasterxml.com/JacksonFAQ

  • 我是否可以在已使用**@ XmlElement**注释的类Person中使用此**@ JsonProperty**注释?我试图覆盖这样的属性值:`@JsonProperty(value ="json_Name")@XmlElement(name ="name_provider")public String getName(){return name; }但是无论如何我的名字值是**name_provider**,而不是**json_Name** (2认同)
  • 是的,虽然它是否有效取决于包含的'AnnotationIntrospector'的优先级(杰克逊自己对JAXB).两者都将被检测到,但是一个注册优先级更高的"胜利". (2认同)

Vij*_*jai 8

通过一些示例,您还可以在 getter 和 setter 中使用它来将其重命名为不同的字段

public class Sample {

    private String fruit;

    @JsonProperty("get_apple")
    public void setFruit(String fruit) {
        this.fruit = fruit;
    }

    @JsonProperty("send_apple")
    public String getFruit() {
        return fruit;
    }

}
Run Code Online (Sandbox Code Playgroud)