SOAP Web服务的复杂对象:ClassCastException

时间:2012-06-01 15:05:27

标签: android web-services soap classcastexception

我正在使用基于this教程的KSOAP2库获取复杂对象的ArrayList:

我能够接收对象的arrayList。问题是当信封只有一个物体时...当我这样做时:

//...Call webservice
Vector<SoapObject> vectorOfSoapObject = (Vector<SoapObject>)envelope.getResponse();
//pass Vector to ArrayList

当我在信封上只有一个物体时,它会在此行返回ClassCastException。当我有更多它工作正常(我调试看到这发生)...

可能是什么问题?

2 个答案:

答案 0 :(得分:1)

当有多个记录时,服务返回Vector<SoapObject>,当只有记录时,它只返回SoapObject
您正在尝试将SoapObject投射到Vector<SoapObject>,因此ClassCastException
这是实现服务的问题。但是,要在最后修复此问题,您应首先获得envelope.getResponse() Object,并在投标前检查ObjectVector<SoapObject>SoapObject的实例。< / p>

Vector<SoapObject> vectorOfSoapObject = null;
Object response = envelope.getResponse();

if( response instanceof Vector){
   Vector<SoapObject> vectorOfSoapObject = (Vector<SoapObject>) response;       
}else if(response instanceof  SoapObject){
    //cast single object
   SoapObject soapObject = (SoapObject) response;
   //initialize vector
   vectorOfSoapObject = new Vector<SoapObject>();
   //add single object to vector. 
   vectorOfSoapObject.add(soapObject);
}

这样你就不必改变你可能在假设你总是得到列表时编写的其他代码

答案 1 :(得分:1)

我能够解决这个问题。使用@Pranalee的建议,我做了这个:

//call webservice
Object o1 = envelope.getResponse();
if(o1 == null){//no devices updated
    Log.d("GetUpdatesThread","o1==null");
} else if(o1.getClass().toString().equals(new SoapObject("", "").getClass().toString())){//one device updated
    Log.d("GetUpdatesThread","class -- soapObject");
    SoapObject result = (SoapObject) envelope.getResponse();
    Device d = convertToDevice(result);
    devicesUpdated.add(d);
} else if (o1.getClass().toString().equals(new Vector().getClass().toString())){//more than one device updated
    Log.d("GetUpdatesThread","class -- vector");
    Vector<SoapObject> vectorOfSoapObject2 = (Vector<SoapObject>)envelope.getResponse();
    for (SoapObject soapObject : vectorOfSoapObject2) {
         Device d = convertToDevice(soapObject);
         devicesUpdated.add(d);
    }  
}