您的位置:首页 > Web前端 > JavaScript

Jackson tips: using @JsonAnyGetter/@JsonAnySetter to create "dyna beans"

2016-05-19 11:44 585 查看
One relatively common "special" POJO is so-called dynamic bean ("dyna-bean"), which is sort of combination of regular bean and basic Java Map; with zero or more properties with known name, and extensible set of 'other' key/value pairs.

Here's what such a POJO might look like:

public class DynaBean
{
// Two mandatory properties
protected final int id;
protected final String name;

// and then "other" stuff:
protected Map<String,Object> other = new HashMap<String,Object>();

public DynaBean(int id, String name)
{
this.id = id;
this.name = name;
}

public int getId() { return id; }
public String getName() { return name; }

public Object get(String name) {
return other.get(name);
}

public void set(String name, Object value) {
other.put(name, value);
}
}


Since Jackson can serialize Bean as well as Maps, what is the problem? As presented, bean would not serialize and deserialize as expected, although it could be modified to just return Map of "other" properties, and deserialize them back. This would work, but
would result in an additional level of wrapping, so that secondary properties would be within a separate JSON Object.

But Jackson can actually be made to work with such POJOs: here is one way to do it:

public class DynaBean
{
// Two mandatory properties
protected final int id;
protected final String name;

// and then "other" stuff:
protected Map<String,Object> other = new HashMap<String,Object>();

// Could alternatively add setters, but since these are mandatory
@JsonCreator
public DynaBean(@JsonProperty("id") int id, @JsonProperty("name") String name)
{
this.id = id;
this.name = name;
}

public int getId() { return id; }
public String getName() { return name; }

public Object get(String name) {
return other.get(name);
}

// "any getter" needed for serialization
@JsonAnyGetter
public Map<String,Object> any() {
return other;
}

@JsonAnySetter
public void set(String name, Object value) {
other.put(name, value);
}
}


And there we have it: serializes and deserializes nicely.

Share and enjoy...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: