jackson serializing Collections.unmodifiable*
Okay, you've run into an edge-ish type case with Jackson. The problem really is that the library will happily use your getter method to retrieve collection and map properties, and only falls back to instantiating these collections/maps if those getter methods return null.
This can fixed by a combination of @JsonProperty/@JsonIgnore
annotations, with the caveat that the @class
property in your JSON output will change.
Code example:
public class Account {
@JsonProperty("memberEmails")
private Map<Integer, String> memberEmails = Maps.newHashMap();
public Account() {
super();
}
public void setMemberEmails(Map<Integer, String> memberEmails) {
this.memberEmails = memberEmails;
}
@JsonIgnore
public Map<Integer, String> getMemberEmails() {
return Collections.unmodifiableMap(memberEmails);
}
}
If you serialize this class with your test code you will get the following JSON:
{
"@class": "misc.stack.pojo.Account",
"memberEmails": {
"10": "[email protected]",
"@class": "java.util.HashMap"
}
}
Which will deserialize correctly.