简体   繁体   中英

How to parse xmlElements with Jackson?

How to parse xmlElements with Jackson? for example my xml is:

<channel>
  <title>Title</title>
  <link>http://example.com</link>
   <item>
     <category>Categ</category>
     <guid>http://1294796429.html</guid>
     <rian:priority xmlns:rian="http://example.com">3</rian:priority>
   </item>
   ...
   <item>... </item>
   ...
</channel>

classes are:

@JacksonXmlRootElement(localName = "channel")
 public static class Channel {
    @JacksonXmlProperty(localName = "title")
    public String title;
    @JacksonXmlProperty(localName = "link")
    public String link;
    @JacksonXmlProperty(localName = "item")
    public List<Item> items;
 }
 public static class Item{
    @JacksonXmlProperty(localName = "category")
    public String category;
    @JacksonXmlProperty(localName = "guid")
    public String guid;
    @JacksonXmlProperty(localName = "rian:priority")
    public String rian:priority;
 }

I'm using it to parse

XmlMapperxmlMapper = new XmlMapper();
Channel mChannel = xmlMapper.readValue(stringXML, Channel.class);

But it doesn't work. Error is Can't cust String to Item

Just need to create class

@JacksonXmlRootElement(localName = "channel")
public class Channel

{
    private String title;
    private String link;
    public Channel(){
    }
    @JacksonXmlProperty(localName = "item")
    @JacksonXmlElementWrapper(useWrapping = false)
    public List<Item> items;
    //----getters...settters
 }

Item class:

public  class Item {
    private String guid;
    private String category;
    public Item(){

    }

}

run

JacksonXmlModule module = new JacksonXmlModule();
        module.setDefaultUseWrapper(false);
        XmlMapper xmlMapper = new XmlMapper(module);
        xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        Channel mChannel = xmlMapper.readValue(in, Channel.class);
        Log.e(LOG_TAG, "getItemsSize: " + mChannel.getItems().size());

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