UnMarshalling XML 给出 null java 对象。
XML:
<?xml version="1.0" encoding="UTF-8"?>
<Items>
<Item Name="John"/>
<Item Name="Jason"/>
</Items>
元素类别:
@XmlRootElement(name = "Items")
@XmlAccessorType(XmlAccessType.FIELD)
public class Items{
@XmlElement
private List<Item> item;
public List<Item> getItem() {
return this.Item;
}
}
项目类别:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Item")
public class Item{
@XmlAttribute
private String name;
public String getName() {
return this.Name;
}
}
UnMarshalls 的 Java 代码:这里 result.getBody 给出 XML 字符串
ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
JAXBContext jaxbContext = JAXBContext.newInstance(Items.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Items itResult = (Items) jaxbUnmarshaller.unmarshal(new StringReader(result.getBody()));
Item 对象始终为 null。如何正确解码 xml? 提前致谢。 :
最佳答案
使用以下类:
Item.java
@XmlRootElement(name = "Item")
public class Item
{
private String name;
public String getName()
{
return this.name;
}
@XmlAttribute(name = "Name" )
public void setName( String name )
{
this.name = name;
}
}
Items.java
@XmlRootElement(name = "Items")
public class Items
{
@XmlElementWrapper( name = "Items")
private List<Item> items = new ArrayList<Item>();
public List<Item> getItemList()
{
return this.items;
}
@XmlElement(name = "Item")
public void setItemList( List<Item> items )
{
this.items = items;
}
}
测试.java
public class Test
{
public static void main( String... args )
{
try
{
JAXBContext jaxbContext = JAXBContext.newInstance( Items.class );
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Items itResult = (Items) jaxbUnmarshaller.unmarshal( new File( "Items.xml" ) );
if ( itResult != null )
{
List<Item> items = itResult.getItemList();
for ( Item item : items )
{
System.out.println( item.getName() );
}
}
}
catch ( Exception e )
{
e.printStackTrace();
}
}
}
您应该获取包含 Item
的 Items
对象。
我所做的更改:
a) 列表中需要有一个 @XmlElementWrapper
,它表示 Items
是 Item
的包装器。
b) 将 @XmlAttribute
移动到 Item.java
c) 将 @XmlElement
移动到 Items.java
关于Java UnMarshall XML 给出 null 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44436405/