Using JAXB (2.2) and Jackson (1.9.13), I have trouble unmarshalling the following JSON object to my POJOs
{
"userId": "foo",
"group_id": "bar"
}
Note that the payload contains both a camelCase and an underscore field.
The POJO generated by xjc for my XML schema is as follows:
public class User {
@XmlElement(required = true)
protected String userId;
@XmlElement(name = "group_id", required = true)
protected String groupId;
public String getUserId() { return userId; }
public void setUserId(String value) { this.userId = value; }
public String getGroupId() { return groupId; }
public void setGroupId(String value) { this.groupId = value; }
}
Jackson fails with the following exception:
org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "group_id"
What I tried so far and failed
1. Use JAXB binding underscoreBinding="asCharInWord"
Using the following JXB binding in my XML schema
<jxb:globalBindings underscoreBinding="asCharInWord"/>
generates the following POJO:
public class User {
@XmlElement(required = true)
protected String userId;
@XmlElement(name = "group_id", required = true)
protected String groupId;
public String getUserId() { return userId; }
public void setUserId(String value) { this.userId = value; }
public String getGroup_Id() { return groupId; }
public void setGroup_Id(String value) { this.groupId = value; }
}
Note that JAXB now generated setters/getters with underscore for group IDs but the group_id
field is still converted to CamelCase. Jackson's object mapper seems to ignore the property getters/setter names and still can't map group_id
to groupId
.
2. Jackson property naming strategy
Using Jackson's PropertyNamingStrategy CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES
I can convert group_id
to groupId
, but now the object mapper fails on the userId
JSON property.
3. Add a JSONProperty
annotation to groupId
Adding a JSONProperty
to the vanilla JAXB generated POJOs actually works
public class User {
/* ... */
@XmlElement(name = "group_id", required = true)
@JSONProperty("group_id")
protected String groupId;
/* ... */
}
However, my XML schema is huge and manual instrumentation of the generated classes is not feasible, since we generate our classes often.
What should I do?
I see the following two remaining options to handle this problem:
- Implement a JAXB plugin that adds a
JSONProperty
annotation to eachXMLElement
with underscore names (my preferred next approach) - Use a custom name generator for XJC as outlined in this Stackoverflow answer.
Have I missed the obvious? thanks for your thoughts.