将SOAP响应转换为xstream对象

时间:2014-08-11 08:53:38

标签: java xstream

我有来自另一个应用程序的Soap响应,我试图使用“XStream”使用下面的代码转换为对象;

XStream xstream = new XStream(new DomDriver());
file file = new File("file.xml");
InputStream inputStream= new FileInputStream(file);
Reader reader = new InputStreamReader(inputStream,"UTF-8");
String reqXMLString = "" //Stream converted to XML
System.out.println(xstream.fromXML(reqXMLString)); **//Error line**

file.xml:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
        <soap:validationErrors>
            <messages>
                <message>
                    <code>1020</code>
                    <text>Filed 1 is mandatory</text>
                </message>                  
            </messages>
        </soap:validationErrors>
    </soap:Body>
</soap:Envelope>

当我尝试将此xml转换为java对象时。我收到了以下错误;

Exception in thread "main" com.thoughtworks.xstream.mapper.CannotResolveClassException: soap:Envelope : soap:Envelope
    at com.thoughtworks.xstream.mapper.DefaultMapper.realClass(DefaultMapper.java:68)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
    at com.thoughtworks.xstream.mapper.DynamicProxyMapper.realClass(DynamicProxyMapper.java:71)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)
    at com.thoughtworks.xstream.mapper.PackageAliasingMapper.realClass(PackageAliasingMapper.java:88)
    at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:38)

我可以知道,如何使用XStream将soap响应转换为java对象

提前致谢。

1 个答案:

答案 0 :(得分:0)

您需要将SOAP主体作为OMElement从响应中作为对象的映射。您可以尝试这样:(假设您要将您的响应(xml文件)映射到的类是ValidationErrors

FileReader fr = new FileReader("file.xml");
XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(fr);
    StAXSOAPModelBuilder smb = new StAXSOAPModelBuilder(xmlStreamReader);
    SOAPEnvelope senv = smb.getSOAPEnvelope();
    OMElement omelement = senv.getBody().getFirstElement();
    try{
        Iterator<OMElement> childIterator = omelement.getChildElements();
        while(childIterator.hasNext()){
        OMElement childEle = childIterator.next();
        String childName = childEle.getLocalName();
        if("validationErrors".equalsIgnoreCase(childName)){
            XStream stream = new XStream(new StaxDriver());
            stream.setClassLoader(ValidationErrors.class.getClassLoader());
            stream.alias("validationErrors", ValidationErrors.class);
            ValidationErrors response = (ValidationErrors)stream.fromXML(childEle.toString());
           }
        }
        catch(XStreamException e){
           e.printStack();
      }