Десериализация XML в POJO с использованием Jackson XmlMapper

Используя аннотации Jackson XmlMapper, как бы десериализовать этот XML в pojo?

<?xml version="1.0" encoding="UTF-8"?>
<open>
   <creds priv="write" type="internal">
      <user>Username1</user>
      <client_token>abcplaudzrbcy37c</client_token>
      <client_secret>0cxDE3LE0000=</client_secret>
   </creds>
   <creds priv="read" type="internal">
      <user>Username1</user>
      <client_token>123plaudzrbcy37c</client_token>
      <client_secret>0cxDE3LE1234=</client_secret>
   </creds>
   <creds priv="none" type="internal">
      <user>Username1</user>
      <client_token>000plaudzrbcy37c</client_token>
      <client_secret>0cxDE3LEabcd=</client_secret>
   </creds>
</open>

Я попытался использовать что-то вроде этого:

@JacksonXmlRootElement(localName = "Open")
public class OpenCredentials {

    @JacksonXmlProperty(localName = "Credentials")
    private Credentials[] credentials;

}


class Credentials {

    @JacksonXmlProperty(isAttribute = true)
    private String priv;

    @JacksonXmlProperty(isAttribute = true)
    private String type;

    @JacksonXmlProperty(localName = "Creds")
    private Creds[] creds;
}


class Creds {

    @JacksonXmlText(value = true)
    private String user;

    @JacksonXmlText(value = true)
    private String client_token;

    @JacksonXmlText(value = true)
    private String client_secret;
}

Когда я пытался использовать XmlMapper readValue(), я получаю следующую ошибку:

com.fasterxml.jackson.databind.JsonMappingException: Duplicate property '' for [simple type, class com.company.data.utils.api.Creds]
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:268)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:243)

Ответ 1

Ваши классы POJO не соответствуют вашему XML. Структура проще, чем вы думали. Смотрите ниже пример:

@JacksonXmlRootElement(localName = "open")
class OpenCredentials {

    @JacksonXmlProperty(localName = "creds")
    @JacksonXmlElementWrapper(useWrapping = false)
    private Credentials[] credentials;

    //getters, setters, toString
}


class Credentials {

    @JacksonXmlProperty(isAttribute = true)
    private String priv;

    @JacksonXmlProperty(isAttribute = true)
    private String type;

    private String user;

    @JacksonXmlProperty(localName = "client_token")
    private String clientToken;

    @JacksonXmlProperty(localName = "client_secret")
    private String clientSecret;

    //getters, setters, toString
}

Простое использование:

XmlMapper mapper = new XmlMapper();
OpenCredentials openCredentials = mapper.readValue(XML, OpenCredentials.class);
System.out.println(openCredentials);

Над печатью программы (для вашего XML):

OpenCredentials{credentials=[Credentials{priv='write', type='internal', user='Username1', client_token='abcplaudzrbcy37c', client_secret='0cxDE3LE0000='}, Credentials{priv='read', type='internal', user='Username1', client_token='123plaudzrbcy37c', client_secret='0cxDE3LE1234='}, Credentials{priv='none', type='internal', user='Username1', client_token='000plaudzrbcy37c', client_secret='0cxDE3LEabcd='}]}

Смотрите также:

  1. jackson-dataformat-xml.
  2. Домашняя страница: Джексон XML-база данных Wiki.

Ответ 2

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
    import java.io.IOException;
    import java.io.StringReader;

    import Parse_XML_to_Java_Objects.OpenCredentials;

    public class parser {
        public static void main(String[] args) throws IOException {
        XmlMapper mapper = new XmlMapper();
        String XML="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + 
                "<open>\r\n" + 
                "   <creds priv=\"write\" type=\"internal\">\r\n" + 
                "      <user>Username1</user>\r\n" + 
                "      <client_token>abcplaudzrbcy37c</client_token>\r\n" + 
                "      <client_secret>0cxDE3LE0000=</client_secret>\r\n" + 
                "   </creds>\r\n" + 
                "   <creds priv=\"read\" type=\"internal\">\r\n" + 
                "      <user>Username1</user>\r\n" + 
                "      <client_token>123plaudzrbcy37c</client_token>\r\n" + 
                "      <client_secret>0cxDE3LE1234=</client_secret>\r\n" + 
                "   </creds>\r\n" + 
                "   <creds priv=\"none\" type=\"internal\">\r\n" + 
                "      <user>Username1</user>\r\n" + 
                "      <client_token>000plaudzrbcy37c</client_token>\r\n" + 
                "      <client_secret>0cxDE3LEabcd=</client_secret>\r\n" + 
                "   </creds>\r\n" + 
                "</open>";
        OpenCredentials openCredentials = mapper.readValue(new StringReader(XML), OpenCredentials.class);
        System.out.println(openCredentials);
        }
    }


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

@JacksonXmlRootElement(localName = "open")
class OpenCredentials {

    @JacksonXmlProperty(localName = "creds")
    @JacksonXmlElementWrapper(useWrapping = false)
    private Credentials[] credentials;

    //getters, setters, toString
}



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

class Credentials {

    @JacksonXmlProperty(isAttribute = true)
    private String priv;

    @JacksonXmlProperty(isAttribute = true)
    private String type;

    @JacksonXmlProperty(localName = "user")
    private String user;

    @JacksonXmlProperty(localName = "client_token")
    private String clientToken;

    @JacksonXmlProperty(localName = "client_secret")
    private String clientSecret;

    //getters, setters, toString
}

Я попробовал приведенный выше код, но получаю сообщение об ошибке,

Исключение в потоке "main" java.lang.NullPointerException по адресу com.fasterxml.jackson.dataformat.xml.deser.FromXmlParser.addVirtualWrapping(FromXmlParser.java:279) по адресу com.fasterxml.jackson.dataformat.xml.deserconrial.ra(WrapperHandlingDeserializer.java:143) в com.fasterxml.jackson.dataformat.xml.deser.WrapperHandlingDeserializer.deserialize(WrapperHandlingDeserializer.java:111) в com.fasterxml.jackson.databind.ObjectMapAj.jj com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3037) в jacksonxml2java.Parser.main(Parser.java:61)