XStream – Root作为对象的集合

我正在使用类似于此的XML有效负载(有关更全面的示例,请查看: http : //api.shopify.com/product.html )。

  ...   ...   

现在我的代码确实有效,但它做的事情看起来确实非常“错误” – 即它将“产品”与List.class相关联。 所以相关代码如下所示:

  xstream.alias( "products", List.class ); xstream.alias( "product", ShopifyProduct.class ); 

这很好,除非我转到使用该xstream实例外部化任何对象时,它总是使用“产品”,这不是我想要的。

我想能够将通用集合映射到标签:

 xstream.alias( "products", ( List ).class ); // way too easy 

或者让以下snipet工作,但目前还没有:

  ClassAliasingMapper mapper = new ClassAliasingMapper( xstream.getMapper( ) ); mapper.addClassAlias( "product", ShopifyProduct.class ); xstream.registerLocalConverter( ShopifyProductResponse.class, "products", new CollectionConverter( mapper ) ); 

我创建了ShopifyProductResponse类来尝试包装ShopifyProduct,但它没有任何告诉我:

com.thoughtworks.xstream.mapper.CannotResolveClassException:products:com.thoughtworks.xstream.mapper.DefaultMapper.realClass(DefaultMapper.java:68)中的产品,位于com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38) )

如果我添加:

 xstream.alias( "products", List.class ); 

然后它消失了…所以在我看来mapperwrapper没有抓住这里 – 可能是因为它寻找ShopifyProductResponse对象并找到一个List而不是 – 我真的不知道。

如果我理解正确,这就是你要找的。 ShoppifyProductResponse.java

 public class ShoppifyProductResponse { private List product; /** * @return the products */ public List getProducts() { return product; } /** * @param products * the products to set */ public void setProducts(List products) { this.product = products; } 

}

还有一个转换器。 UnMarshalling可能看起来像这样。

 public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { /** * Tune the code further.. */ ShoppifyProductResponse products = new ShoppifyProductResponse(); List lst = new ArrayList(); while (reader.hasMoreChildren()) { reader.moveDown(); ShoppifyProduct thisProduct = (ShoppifyProduct) context.convertAnother(products, ShoppifyProduct.class); lst.add(thisProduct); reader.moveUp(); } products.setProducts(lst); return products; } 

你可以注册为,

  XStream stream = new XStream(); stream.alias("products", ShoppifyProductResponse.class); stream.registerConverter(new ShoppifyConverter()); stream.alias("product", ShoppifyProduct.class); 

我试过这个,它的效果非常好。 试一试,让我知道。