使用杰克逊xml映射器将xml反序列化为pojo

时间:2018-08-12 02:50:56

标签: java deserialization xmlmapper

我正在使用Jackson XML映射器将XML反序列化为POJO。 XML看起来像

<person>
 <agency>
        <phone>111-111-1111</phone>
 </agency>
</person>

我的课看起来像

class Person
{
 @JacksonXmlProperty(localName="agency", namespace="namespace")
 private Agency agency;
 //getter and setter
}
class Agency
{
 @JacksonXmlElementWrapper(useWrapping = false)
 @JacksonXmlProperty(localName="phone", namespace="namespace")
 private List<AgencyPhone> phones;
 //getter and setter
}
class AgencyPhone
{
  private Phone phone;
  //getter and setter
}
class Phone
{
 private String number;
 //getter and setter
}

我想将电话号码设置为“电话”类别中的号码。我无法更改XML或类的构造方式。我收到无法构造resolved.agency.AgencyPhone错误的实例,并创建了一个AgencyPhone构造函数

class AgencyPhone{
{
  private Phone phone;
  public AgencyPhone(Phone phone)
  {
      this.phone = phone;
   }
  }

但是那没有用。那么如何反序列化嵌套实例。

1 个答案:

答案 0 :(得分:1)

您可以编写自己的自定义解串器来实现此目的。这是让您入门的代码:

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.io.IOException;

public class Test {
  public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
    XmlMapper mapper = new XmlMapper();
    final SimpleModule module = new SimpleModule("configModule",   com.fasterxml.jackson.core.Version.unknownVersion());
    module.addDeserializer(Person.class, new DeSerializer());
    mapper.registerModule(module);
    // Person readValue = mapper.readValue(<xml source>);
  }
}

class DeSerializer extends StdDeserializer<Person> {

  protected DeSerializer() {
    super(Person.class);
  }

  @Override
  public Person deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    // use p.getText() and p.nextToken to navigate through the xml and construct Person object
    return new Person();

  }
}