我正在使用类似于此的XML有效负载(有关更全面的示例,请查看:http://api.shopify.com/product.html).
<products type="array">
<product>
...
</product>
<product>
...
</product>
</products>
Run Code Online (Sandbox Code Playgroud)
现在我的代码确实有效,但它做的事情似乎真的"错误" - 即它将"产品"与List.class相关联.所以相关代码如下所示:
xstream.alias( "products", List.class );
xstream.alias( "product", ShopifyProduct.class );
Run Code Online (Sandbox Code Playgroud)
这很好,除非我转到使用该xstream实例外部化任何对象时,它总是使用"产品",这不是我想要的.
我想要能够将通用集合映射到标签:
xstream.alias( "products", ( List<ShopifyProduct> ).class ); // way too easy
Run Code Online (Sandbox Code Playgroud)
或者让以下snipet工作,但目前还没有:
ClassAliasingMapper mapper = new ClassAliasingMapper( xstream.getMapper( ) );
mapper.addClassAlias( "product", ShopifyProduct.class );
xstream.registerLocalConverter( ShopifyProductResponse.class, "products", new CollectionConverter( mapper ) );
Run Code Online (Sandbox Code Playgroud)
我创建了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 );
Run Code Online (Sandbox Code Playgroud)
然后它消失了...所以在我看来mapperwrapper没有抓住这里 - 可能是因为它寻找ShopifyProductResponse对象并找到一个List而不是 - 我真的不知道.
如果我理解正确,这就是你要找的. ShoppifyProductResponse.java
public class ShoppifyProductResponse {
private List<ShoppifyProduct> product;
/**
* @return the products
*/
public List<ShoppifyProduct> getProducts() {
return product;
}
/**
* @param products
* the products to set
*/
public void setProducts(List<ShoppifyProduct> products) {
this.product = products;
}
Run Code Online (Sandbox Code Playgroud)
}
还有一个转换器.UnMarshalling可能看起来像这样.
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
/**
* Tune the code further..
*/
ShoppifyProductResponse products = new ShoppifyProductResponse();
List<ShoppifyProduct> lst = new ArrayList<ShoppifyProduct>();
while (reader.hasMoreChildren()) {
reader.moveDown();
ShoppifyProduct thisProduct = (ShoppifyProduct) context.convertAnother(products,
ShoppifyProduct.class);
lst.add(thisProduct);
reader.moveUp();
}
products.setProducts(lst);
return products;
}
Run Code Online (Sandbox Code Playgroud)
你可以注册为,
XStream stream = new XStream();
stream.alias("products", ShoppifyProductResponse.class);
stream.registerConverter(new ShoppifyConverter());
stream.alias("product", ShoppifyProduct.class);
Run Code Online (Sandbox Code Playgroud)
我试过这个,它的效果非常好.试一试,让我知道.