当前位置: 首页 > 知识库问答 >
问题:

没有从String值('E1')反序列化的String参数构造函数/工厂方法

寇夜洛
2023-03-14

无法将xml转换为java pojo对象。请查看以下详细信息:-

输入xml-

<?xml version='1.0' encoding='UTF-8'?>
<Company>
<Employee>
<Name>E1</Name>
<Id>123</Id>
</Employee>
<Employee>
<Name>E2</Name>
<Id>678</Id>
</Employee>
</Company>

pom.xml有依赖关系:-

<dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>2.9.6</version>
</dependency>

公司Java语言

package com.test;
import java.util.List;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;

@JacksonXmlRootElement
public class Company {
    
    @JacksonXmlProperty(localName = "Employee")
    private List<Employee> employee;
    
    public Company() {}

    public Company(List<Employee> employee) {
        super();
        this.employee = employee;
    }

    public List<Employee> getEmployee() {
        return employee;
    }

    public void setEmployee(List<Employee> employee) {
        this.employee = employee;
    }

    
}

受雇者Java语言

package com.test;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;

public class Employee {
    
    @JacksonXmlProperty(localName = "Name")
    private String name;
    
    @JacksonXmlProperty(localName = "Id")
    private String id;
    
    public Employee() {}

    public Employee(String name, String id) {
        super();
        this.name = name;
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
    
    

}

将xml转换为java代码:-

JacksonXmlModule module = new JacksonXmlModule();
XmlMapper objectMapper = new XmlMapper(module);
module.setDefaultUseWrapper(false);
Company comapny = objectMapper.readValue(xml,Company.class);

下面的错误我在转换xml到pojo时得到

线程“main”com中出现异常。fasterxml。杰克逊。数据绑定。exc.MismatchedInputException:无法构造com的实例。测验Employee(尽管至少存在一个创建者):在[源:(StringReader);行:4,列:7](通过引用链:com.test.Employee[“Company”]处没有字符串参数构造函数/工厂方法从字符串值('E1')反序列化-

共有1个答案

吕寒
2023-03-14

问题在于全局模块的使用。在反序列化中设置DefaultUseWrapper(false),而DefaultUseWrapper的使用应限于嵌套集合列表

@JacksonXmlRootElement
public class Company {
    
    @JacksonXmlProperty(localName = "Employee")
    @JacksonXmlElementWrapper(useWrapping = false)
    private List<Employee> employee;
    
    ...other fields, setters, getters and constructors from your code
}

您必须删除模块。设置DefaultUseWrapper(false)并重写主类,如下所示:

JacksonXmlModule module = new JacksonXmlModule();
XmlMapper objectMapper = new XmlMapper(module);
Company company = objectMapper.readValue(xml,Company.class);
System.out.println(objectMapper.writeValueAsString(company));
 类似资料: