问题
I have a class defined as follows:
public class Contact implements Serializable
{
private final static long serialVersionUID = 1L;
@XmlElement(name = "last-name", required = true)
protected String lastName;
@XmlElement(name = "first-name", required = true)
protected String firstName;
@XmlElement(required = true)
protected String id;
@XmlElement(name = "primary-phone")
protected String primaryPhone;
@XmlElement(name = "cellular-phone")
protected String cellularPhone;
}
This class is being used to generate marshalled JSON versions which are communicated over the internet. On the receiving end I'm trying to unmarshall the JSON, but I'm having difficulty because of the difference in naming, i.e. for example the unmarshalling library expects a variable named primaryPhone
, not primary-phone
which is what I have at the receiving end.
Besides pre-processing the received JSON text to manually replace instances of primary-phone
with primaryPhone
, is there some other more automated way to avoid this problem ? The problem with manually converting strings is that tomorrow if the Class definition changes, the code I'm writing will also need to be updated.
Here's a code snippet showing what I'm currently doing without any manually string conversion:
String contact = "\"last-name\": \"ahmadka\"";
ObjectMapper objMapper = new ObjectMapper();
Contact cObj = objMapper.readValue(contact, Contact.class);
But with the above code I get an exception on the last line reading this:
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "last-name" (class Contact), not marked as ignorable (5 known properties: "lastName", "cellularPhone", "id", "primaryPhone", "firstName", ])
at ...........//rest of the stack
回答1:
Jackson by default doesn't know about JAXB annotations (i.e. @XmlRootElement
). It needs to be configured with an external module in order to have this capability. On the server, you most likely have this without even knowing it.
On the client side if you want to configure the ObjectMapper
, then you need to add the following module:
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>${jackson2.version}</version>
</dependency>
Then just register the JAXB annotations module.
ObjectMapper objMapper = new ObjectMapper();
mapper.registerModule(new JaxbAnnotationModule());
来源:https://stackoverflow.com/questions/38731868/unmarshalling-json-by-reversing-the-affect-of-xmlelement-renaming