【问题标题】:How to parse xmlElements with Jackson?如何用 Jackson 解析 xmlElements?
【发布时间】:2015-12-29 20:32:51
【问题描述】:

如何用 Jackson 解析 xmlElements? 例如我的 xml 是:

<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>

类是:

@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;
 }

我用它来解析

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

但它不起作用。错误是Can't cust String to Item

【问题讨论】:

    标签: java android xml parsing jackson


    【解决方案1】:

    只需要创建类

    @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
     }
    

    物品类别:

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

    }

    运行

    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());
    

    【讨论】:

      猜你喜欢
      • 2018-11-07
      • 1970-01-01
      • 2017-02-19
      • 2016-07-27
      • 1970-01-01
      • 2012-07-05
      • 2018-06-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多