gpt4 book ai didi

java - 反序列化时的 xstream 转换异常

转载 作者:太空宇宙 更新时间:2023-11-04 13:57:18 25 4
gpt4 key购买 nike

使用 xstream 反序列化时,我遇到以下异常:

com.thoughtworks.xstream.converters.ConversionException: Element service of type com.config.Service is not defined as field in type com.config.Service

---- Debugging information ----

class : com.config.ServiceNServiceConfigurations

required-type : com.config.Service

path : /root/services/service

我的 XML 是:

<root>
<services>
<service>
<Id>10</Id>
<Name>CM</Name>
</service>
<service>
<Id>11</Id>
<Name>TM</Name>
</service>
</services>
<serviceConfigurations>
<serviceConfiguration>
<Key>XYZ</Key>
<Value>42</Value>
</serviceConfiguration>
<serviceConfiguration>
<Key>ABC</Key>
<Value>5</Value>
</serviceConfiguration>
</serviceConfigurations>
</root>

我创建了一个与根标签相对应的类,如下所示:

public class ServiceNServiceConfigurations implements Serializable {
private List<ServiceConfiguration> serviceConfigurations;
private List<Service> services;
// setter and getter methods
}
public class Service implements Serializable {
private String Id;
private String Name;
// setter and getter methods
}
public class ServiceConfiguration implements Serializable{
private String key;
private String value;
// setter and getter methods
}

在反序列化测试类中,我编写了以下代码:

   XStream xstream = new XStream();
xstream.alias("root", com.config.ServiceNServiceConfigurations.class);
xstream.alias("service",com.config.Service.class);
xstream.alias("serviceConfiguration",com.config.ServiceConfiguration.class);
xstream.addImplicitCollection(ServiceNServiceConfigurations.class, "services", Service.class);
xstream.addImplicitCollection(ServiceNServiceConfigurations.class, "serviceConfigurations", ServiceConfiguration.class);
xstream.aliasField("Key", com.config.ServiceConfiguration.class, "key");
xstream.aliasField("Value", com.config.ServiceConfiguration.class, "value");
At below line Conversion Exception is coming
obj = xstream.fromXML(xmlSerialized);

请指导我哪里出错了。

谢谢

最佳答案

您应该删除 addImplicitCollection 配置,因为您的集合不是隐式的。

XStream xstream = new XStream();
xstream.alias("root", com.config.ServiceNServiceConfigurations.class);
xstream.alias("service",com.config.Service.class);
xstream.alias("serviceConfiguration",com.config.ServiceConfiguration.class);
xstream.aliasField("Key", com.config.ServiceConfiguration.class, "key");
xstream.aliasField("Value", com.config.ServiceConfiguration.class, "value");

如果它们是隐式的,您的 xml 将如下所示:

<root>
<serviceConfiguration>
<Key>XYZ</Key>
<Value>42</Value>
</serviceConfiguration>
<serviceConfiguration>
<Key>ABC</Key>
<Value>5</Value>
</serviceConfiguration>
<service>
<Id>10</Id>
<Name>CM</Name>
</service>
<service>
<Id>11</Id>
<Name>TM</Name>
</service>
</root>

关于java - 反序列化时的 xstream 转换异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29692015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com