这是我的班级字段。
@XStreamAlias("OrgEntity")
public class OrgEntity implements Serializable {
private static final long serialVersionUID = 2L;
private static final int MAX_SHARE_PERCENTAGE = 100;
private static final byte MIN_ORG_NAME_LENGTH = 2;
public static Map<String, OrgEntity> allOrgMap;
@XStreamAlias("entityName")
@XStreamAsAttribute
private String entityName;
private OrgType type;
private float sharesPortionHeldBy;
private double authorisedCapital;
private String parentCompanyName;
private Human ceo;
private Map<ShareHolder, Float> shareHoldersMap;
....
}
这是我需要阅读的xml:
<OrgEntity entityName="nonParentCompany">
<type>ZAO</type>
<sharesPortionHeldBy>13.0</sharesPortionHeldBy>
<authorisedCapital>1000000.0</authorisedCapital>
<ceo surname="Narishkin" firstName="Denis" middleName="Ven"/>
<shareHoldersMap>
<entry>
<ShareHolder surname="Trump" firstName="Don" middleName="J">
<shareHolderPortfolioMap>
<shareHolderAsset>
<entry>
<string>nonParentCompany</string>
<float>5.0</float>
</entry>
</shareHolderAsset>
<outer-class reference="../.."/>
</shareHolderPortfolioMap>
<currCom reference="../../../.."/>
<sharesNumberCurrComp>5.0</sharesNumberCurrComp>
</ShareHolder>
<float>5.0</float>
</entry>
<entry>
<ShareHolder surname="Smith" firstName="Adam" middleName="A">
<shareHolderPortfolioMap>
<shareHolderAsset>
<entry>
<string>nonParentCompany</string>
<float>8.0</float>
</entry>
</shareHolderAsset>
<outer-class reference="../.."/>
</shareHolderPortfolioMap>
<currCom reference="../../../.."/>
<sharesNumberCurrComp>8.0</sharesNumberCurrComp>
</ShareHolder>
<float>8.0</float>
</entry>
</shareHoldersMap>
</OrgEntity>
如何通过XStream读取此xml?我尝试使用下面的代码,但它失败了。我收到你的例外是" Exception in thread "main" com.thoughtworks.xstream.InitializationException: No field "shareHoldersMap" for implicit collection "
你能给我一些建议,为了能够阅读xml,我该怎么做。提前致谢。
public static void main(String[] args) {
OrgEntity o = DataForRunners.createDataForBasicFile15OrgsWithShareHoldingsUpdateForXML().get(0);
String xmlOrgObj = "src/main/java/com/.... ";
new XStreamDecorator<OrgEntity>(o, xmlOrgObj);
XStream xstream = new XStream(new DomDriver());
xstream.alias("OrgEntity", OrgEntity.class);
xstream.alias("entityName", OrgEntity.class);
xstream.alias("type", OrgType.class);
xstream.alias("ceo", Human.class);
xstream.addImplicitCollection(HashMap.class, "shareHoldersMap");
InputStream in = null;
try {
in = new FileInputStream(xmlOrgObj);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OrgEntity var =(OrgEntity) xstream.fromXML(in);
System.out.println(var);
}
答案 0 :(得分:1)
在XStream 1.4.5及更高版本中,您可以使用
NamedMapConverter
所以在你的情况下你可以尝试这样的事情:
XStream xstream = new XStream();
NamedMapConverter namedMapConverter = new NamedMapConverter(xstream.getMapper(), "entry", "key", ShareHolder.class, "value", Float.class);
xstream.registerConverter(namedMapConverter);