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...

本文介绍了一种结合普通Bean和基本Java Map特性的特殊POJO——动态Bean,并展示了如何使用Jackson进行序列化和反序列化。通过添加@JsonAnyGetter和@JsonAnySetter注解,可以实现动态Bean中额外属性的有效处理。
692

被折叠的 条评论
为什么被折叠?



