2010-06-28 3 views
5

나는 이와 비슷한 XML 페이로드를 사용하고 있습니다 (보다 포괄적 인 예를 보려면 체크 아웃 : http://api.shopify.com/product.html).XStream - 객체 모음으로 루트

<products type="array"> 
    <product> 
     ... 
    </product> 
    <product> 
     ... 
    </product> 
</products> 

지금 현재 내 코드가 작동하지 않습니다,하지만 정말 정말 "잘못된"것으로 보인다 뭔가를하고 - 즉 그것은 List.class와 "제품"을 연결합니다. 그래서 관련 코드는 다음과 같습니다

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

이 내가 고토 항상 내가 원하는 것이 아니다 물론 "제품"을 사용하는 XStream을 인스턴스와 개체를 외부화하는 경우를 제외하고 괜찮습니다.

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

I : 지금하지 않는,하려면 다음 snipet을

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

또는 얻을 :

나는 태그에 일반적인 컬렉션을지도 할 수 있도록 하나 싶습니다 ShopifyProductResponse 클래스를 만들어서 ShopifyProduct를 래핑했지만 그 중 아무 것도 말해주지 못했습니다 :

com.thoughtworks.xstream.mapper.CannotResolveClassException : products : products 0 com.thoughtworks.xstream.mapper.MapperWrapper.realClass에서 com.thoughtworks.xstream.mapper.DefaultMapper.realClass (DefaultMapper.java:68) 에서(MapperWrapper.java:38)

내가 추가하는 경우 :

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

그때 그것은 사라집니다. 매퍼 래퍼가 여기에 잡히지 않고있는 것 같습니다. 아마 ShopifyProductResponse 개체를 찾고 목록을 찾는 것이기 때문에 나는 정말로 모른다.

답변

6

제가 이해한다면, 당신이 찾고있는 것입니다. 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; 
} 

}

그리고 이것에 대한 변환기. 언 마샬링은 다음과 같이 보일 수 있습니다.

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

그리고 당신은으로 등록 할 수

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

내가 이것을 시도하고 꽤 많은 벌금을 작동합니다. 시도해보고 알려줘.

+0

좋아, 나는 이것에 대해 주위에 매달려 여분의 래퍼 객체를 갖는 아이디어를 정말로 좋아하지 않는다. 그러나 그것은 의도 된대로 작동하며,이 시점에서 정말로 중요한 것은 무엇인가 - 감사합니다! – Lypheus

관련 문제