<staging>
<stage>
<name>aaaa</name>
<taskName>aa</taskName>
<taskName>qwqwse</taskName>
<taskName>qwe</taskName>
<iconName>asdad</iconName>
<iconName>dasd</iconName>
</stage>
<stage>
<name>dasda</name>
<taskName>asdak</taskName>
<taskName>dasdk1</taskName>
<taskName>dasdask2</taskName>
<iconName>dasdn</iconName>
<iconName>dasdcon</iconName>
</stage>
</staging>
这是我的java类:
@XStreamAlias("stage")
public class Stage {
private String name;
private List<String> taskName;
private List<String> iconName;
}
我正在使用XStream 1.4.2将该XML数据转换为Java对象。
我见过几个SO帖子,但它仍然无法解决我的问题。
抛出以下异常:
com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter$DuplicateFieldException: Duplicate field taskName
---- Debugging information ----
field : taskName
class : com.thbs.soaconnect.model.configuration.Stage
required-type : com.thbs.soaconnect.model.configuration.Stage
converter-type : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
path : /soaConnect/staging/stage/taskName[2]
line number : 28
class[1] : java.util.ArrayList
converter-type[1] : com.thoughtworks.xstream.converters.collections.CollectionConverter
class[2] : com.thbs.soaconnect.model.configuration.Configuration
version : null
我之前尝试过以下方式:
xstream.addImplicitCollection(Stage.class,"taskName", String.class);
xstream.addImplicitCollection(Stage.class,"iconName", String.class);
虽然它不会抛出任何异常,但它无法读取值,每个元素都有。
你能帮我吗?答案 0 :(得分:6)
答案就在调试信息中
Duplicate field taskName
path : /soaConnect/staging/stage/taskName[2]
<强>更新强>
看看这个answer我认为你缺少一些注释
@XStreamAlias("stage")
public class Stage {
private String name;
@XStreamImplicit(itemFieldName="taskName")
private List<String> tasks;
@XStreamImplicit(itemFieldName="iconName")
private List<String> icons;
}
答案 1 :(得分:4)
您不必在Stage类中添加任何内容。只需为Stage类添加适当的别名,然后使用addImplicitCollections。
XML Input :
<stage>
<name>dasda</name>
<taskName>asdak</taskName>
<taskName>dasdk1</taskName>
<taskName>dasdask2</taskName>
<iconName>dasdn</iconName>
<iconName>dasdcon</iconName>
</stage>
Code for Stage Class :
public class Stage {
private String name;
private List<String> taskName;
private List<String> iconName;
}
Code to retrieve parse XML using xtream object :
Xstream.alias("stage", Stage.class);
Xstream.addImplicitCollection(Stage.class,"taskName",String.class);
Xstream.addImplicitCollection(Stage.class,"iconName",String.class);
It worked for me.