Jaxb注释使用Jackons

时间:2015-08-26 10:43:45

标签: json jaxb jackson

我有一个简单的json数据,我的pojo用jaxb注释注释。我想在不使用json注释的情况下反序列化它。

(必须这样做,请不要建议在pojo上同时使用这两个注释)。

杰克逊确认(这是我所理解的)它可能通过 http://wiki.fasterxml.com/JacksonJAXBAnnotations https://github.com/FasterXML/jackson-module-jaxb-annotations

但是当我运行代码时,它不能提供所需的结果。

这是pojo。

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Simple_root")
@XmlAccessorType(XmlAccessType.FIELD)
public class Simple {
    @XmlElement(name = "x")
    private String firstName;
    @XmlElement(name = "y")
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

下面是使用jackson ObjectMapper的两个测试方法的测试类。

import org.junit.Assert;
import org.junit.Test;

import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;

public class XmlMapperTest {

    @Test
    public void jsonDeserialize_using_JaxbAnnotationIntrospector() throws Exception {
        ObjectMapper jsonMapper = new ObjectMapper();
        jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
        jsonMapper.getDeserializationConfig().with(introspector);
        jsonMapper.getSerializationConfig().with(introspector);

        Simple simple = jsonMapper.readValue("{\"Simple_root\": {\"x\": \"2\", \"y\": \"4\"}}", Simple.class);
        Assert.assertNotNull(simple.getFirstName());
        Assert.assertNotNull(simple.getLastName());
    }

    @Test
    public void jsonDeserialize_using_JaxbAnnotationModule() throws Exception {
        ObjectMapper jsonMapper = new ObjectMapper();
        jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        JaxbAnnotationModule jaxbModule = new JaxbAnnotationModule();
        jsonMapper.registerModule(jaxbModule);

        Simple simple = jsonMapper.readValue("{\"Simple_root\": {\"x\": \"2\", \"y\": \"4\"}}", Simple.class);
        Assert.assertNotNull(simple.getFirstName());
        Assert.assertNotNull(simple.getLastName());
    }
}

任何帮助都会受到赞赏,因为我知道我肯定错过了一天中和睡前2小时都找不到的东西。

0 个答案:

没有答案