如何用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
答案 0 :(得分:0)
只需要创建类
@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());