如何将 JSON 字段名称映射到不同的对象字段名称? [英] How to map JSON field names to different object field names?

查看:116
本文介绍了如何将 JSON 字段名称映射到不同的对象字段名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下 jax-b 注释在 Jackson json 注释中的等效方式是什么?

What is the equiv way in Jackson json annotation for the following jax-b annotations?

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

I need to produce json rather than xml and need to know the conventional jackson annotations that is equivalently denoted in jax-b.

  1. 重命名字段.
  2. 使用 getter 代替字段.

如果 json/xml 元素名称是 java 保留字,这些特性尤其重要如new"、public"、static"等

These features are especially crucial if the json/xml element name is a java reserved word like "new", "public", "static", etc.

因此我们必须将 POJO 字段分别命名为_new_"、_public_"、_static_"等,

So that we have to name the POJO fields as "_new_", "_public_", "_static_", etc, respectively,

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

but use jax-b annotation to rename them back to "new", "public", "static", etc in the generated XML (and json) elements.

重命名字段

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

重定向到使用属性 getter(我认为这是在 jax-b 中的做法)

Redirect to using property getter (I think this is how it is done in 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_;}
}

推荐答案

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

Probably it's a bit late but anyway..

您只需添加即可重命名属性

you can rename a property just adding

@JsonProperty("contractor")

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

And by default Jackson use the getter and setter to serialize and deserialize.

更多详细信息:http://wiki.fasterxml.com/JacksonFAQ

这篇关于如何将 JSON 字段名称映射到不同的对象字段名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆