Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

java - How to map JSON field names to different object field names?

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

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

  1. rename a field.
  2. use getters instead of fields.

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

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

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

Renaming a field

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

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_;}
}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Probably it's a bit late but anyway..

you can rename a property just adding

@JsonProperty("contractor")

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

For more detailed information: http://wiki.fasterxml.com/JacksonFAQ


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...