I am facing below exception while deserialization using 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
My XML is :
<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>
I created one class corresponding to root tag as below :
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
}
In Test class for deserialization , i wrote below code :
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);
Kindly guide me where I am going wrong.
Thanks
You should remove addImplicitCollection
configurations, because your collections are not implicit.
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");
If they would be implicit your xml would look like this:
<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>