我有一个类定义如下:
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;
}
此类用于生成通过Internet传送的编组JSON版本。在接收端,我正在尝试解组JSON,但由于命名的不同,我遇到了困难,例如,解组库需要一个名为primaryPhone
的变量,而不是primary-phone
,这就是我在接收端所拥有的。
除了预处理收到的JSON文本以手动用primary-phone
替换primaryPhone
的实例外,还有其他一些更自动化的方法可以避免这个问题吗?手动转换字符串的问题是明天,如果类定义发生变化,我写的代码也需要更新。
这是一个代码片段,显示我目前正在做的事情,没有任何手动字符串转换:
String contact = "\"last-name\": \"ahmadka\"";
ObjectMapper objMapper = new ObjectMapper();
Contact cObj = objMapper.readValue(contact, Contact.class);
但是使用上面的代码我在最后一行读到这个:
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
杰克逊默认不了解JAXB注释(即@XmlRootElement
)。它需要配置外部模块才能具备此功能。在服务器上,你很可能甚至不知道它。
在客户端,如果要配置ObjectMapper
,则需要添加following module:
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>${jackson2.version}</version>
</dependency>
然后只需注册JAXB注释模块。
ObjectMapper objMapper = new ObjectMapper();
mapper.registerModule(new JaxbAnnotationModule());