简体   繁体   中英

FasterXML: Could not deserialize form XML to POJO

I'm trying to deserialize XML.

<server>
    <url>localhost</url>
    <port>8080</port>
</server>

to POJO

class Storage {
    private Server server;
}

class Server {
    private String url;
    private Integer port;
}

Here is my fire code

resources = new FileInputStream("/resources/config/" + file);
mapper = new ObjectMapper();
storage = mapper.readValue(resources, Storage.class);

But it doesn't work.

com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')

I tried to add JAX-B annotation to Storage and Server class, but the same error occurred.

UPD

When I add mapper = new XmlMapper(); that I recieve com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "url"

First, ObjectMapper instances are meant to deserialize JSON. So you won't be able to use it as is. Use a XmlMapper .

Second, the root of your XML, <server> , contains two elements, <url> and <port> . But your root Java type, Storage ,

storage = mapper.readValue(resources, Storage.class);

contains only one, server . So you need a wrapper element to act as root in the XML

<Storage>
    <server>
        <url>localhost</url>
        <port>8080</port>
    </server>
</Storage>

Also, I'm assuming you meant for

private Server url;

to be

private String url;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM