反序列化的xstream转换异常

时间:2015-04-17 06:37:54

标签: java xstream

我在使用xstream进行反序列化时面临异常:

  

com.thoughtworks.xstream.converters.ConversionException:com.config.Service类型的元素服务未定义为com.config.Service类型中的字段

     

----调试信息----

     

class:com.config.ServiceNServiceConfigurations

     

required-type:com.config.Service

     

路径:/ 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>

我创建了一个对应于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);

请指导我出错的地方。

由于

1 个答案:

答案 0 :(得分:0)

您应该删除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>