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

(尽管至少有一个Creator存在):没有String-参数构造函数/工厂方法从String值反序列化('12')

姚丰羽
2023-03-14

以下方法transtToObject使用Jackson将XML转换为Object。我得到以下错误:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.test.Student` 
(although at least one Creator exists):no String-argument constructor/factory method to deserialize from String value ('12')

以下是核心类:

    private Students convertToObject(String xml) {
    XmlMapper xmlMapper = new XmlMapper();
    Students matchedObjects = null;

    try {
         System.out.println(xml);
         matchedObjects = xmlMapper.readValue(xml, Students.class);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }

    System.out.println(matchedObjects);

    return matchedObjects;
}

这是输入XML:

<students>
<student><id>12</id><surname>DOE</surname><givenName>JOHN</givenName><marks>98.928</marks></student>
<student><id>13</id><surname>PRICE</surname><givenName>MIKE</givenName><marks>90.8444</marks> </student>
</students>

以下是两个POJO:

@Getter @Setter @AllArgsConstructor @NoArgsConstructor @ToString
@JacksonXmlRootElement(localName = "student")
public class Student {
    String id;
    String givenName;
    String surname;
    String marks;
}

@Getter @Setter @AllArgsConstructor @NoArgsConstructor @ToString
@JacksonXmlRootElement(localName = "students")
public class Students {
    @JacksonXmlProperty(localName = "student")
    private List<Student> student;
}

这是pom文件中的依赖项。

    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
        <version>2.11.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.11.1</version>
    </dependency>

共有1个答案

慕容超
2023-03-14

您不需要包装类。取消这个XML负载为List

CollectionType studentsListType = xmlMapper.getTypeFactory().constructCollectionType(List.class, Student.class);
List<Student> students = xmlMapper.readValue(xmlFile, studentsListType);

 类似资料: