XStream - Root as a collection of objects

夙愿已清 提交于 2019-11-29 02:32:43

If i understand correct, this is what you are looking for. 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;
}

}

And a converter for this. UnMarshalling might look like this.

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;
}

And you can register it as,

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

I have tried this and it works pretty much fine. Give it a try and let me know.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!