2010-06-22 23 views
5

Utilizo una lib ksoap2 para comunicarme desde el cliente de Android con el servicio web SOAP. El equipo de ksoap hizo un gran trabajo, pero el problema es que no hay ningún buen ejemplo de cómo usarlo correctamente en diferentes aspectos. Por ejemplo recibo en respuesta jabón siguientes datos:Analizando la respuesta ksoap2

anyType{ 
    StatusSetting=anyType{Id=1; Name=Til afskrivning; LocationId=1; Editable=true; Default=true; Transcribed=false; }; 
    StatusSetting=anyType{Id=2; Name=Afskrevet; LocationId=1; Editable=false; Default=false; Transcribed=true; }; 
    ... 
} 

Es un objeto complejo, o más bien una colección de objetos StatusSetting. Cuando intento obtener una propiedad de SoapObject, solo tengo 1 propiedad con todos los datos como una cadena. No se puede analizar como json también. Increíble que nadie se encontró con el mismo problema con respecto a la popularidad de Android está ganando. Sería genial saber si alguien resolvió este problema y cómo. Gracias.

Respuesta

4
SoapObject countryDetails = (SoapObject)envelope.getResponse(); 
System.out.println(countryDetails.toString()); 

ArrayList list = new ArrayList(countryDetails.getPropertyCount()); 
lv_arr = new String[countryDetails.getPropertyCount()]; 
for (int i = 0; i < countryDetails.getPropertyCount(); i++) { 
    Object property = countryDetails.getProperty(i); 
    if (property instanceof SoapObject) { 
     SoapObject countryObj = (SoapObject) property; 
     String countryName = countryObj.getProperty("countryName").toString(); 
     list.add(countryName); 
    } 
} 

espero que debería funcionar

+0

en el caso anterior, supongamos que countryName = "" luego analiza su valor como anyType ... es decir. String countryName = anyType ... ¿Alguna solución para eso? –

8

Por ejemplo, su respuesta:

anyType 
{ 
    FOO_DEALS=anyType 
    { 
     CATEGORY_LIST=anyType 
     { 
     CATEGORY=Books; 
     CATEGORY_URL=books_chennai; 
     CATEGORY_ICON=http://deals.foo.com/common/images/books.png; 
     CATEGORY_COUNT=1045; 
     TYPE=1; 
     SUPERTAG=Books; 
     }; 
     CATEGORY_LIST=anyType 
     { 
      CATEGORY=Cameras; 
      CATEGORY_URL=cameras_chennai; 
      CATEGORY_ICON=http://deals.foo.com/common/images/cameras.png; 
      CATEGORY_COUNT=152; 
      SUPERTAG=Cameras; 
      TYPE=1; 
     }; 
    }; 
} 

para solicitar y análisis hacen así:

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); 
      // Add the input required by web service 
      request.addProperty("city","chennai"); 
      request.addProperty("key","10000"); 

      SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER11); 
      envelope.setOutputSoapObject(request); 

      // Make the soap call. 
      androidHttpTransport.call(SOAP_ACTION, envelope); 

      // Get the SoapResult from the envelope body. 
      resultRequestSOAP = (SoapObject) envelope.bodyIn; 


      System.out.println("********Response : "+resultRequestSOAP.toString()); 

      SoapObject root = (SoapObject) resultRequestSOAP.getProperty(0); 
      SoapObject s_deals = (SoapObject) root.getProperty("FOO_DEALS"); 

      StringBuilder stringBuilder = new StringBuilder(); 

      System.out.println("********Count : "+ s_deals.getPropertyCount()); 

      for (int i = 0; i < s_deals.getPropertyCount(); i++) 
      { 
       Object property = s_deals.getProperty(i); 
       if (property instanceof SoapObject) 
       { 
        SoapObject category_list = (SoapObject) property; 
        String CATEGORY = category_list.getProperty("CATEGORY").toString(); 
        String CATEGORY_URL = category_list.getProperty("CATEGORY_URL").toString(); 
        String CATEGORY_ICON = category_list.getProperty("CATEGORY_ICON").toString(); 
        String CATEGORY_COUNT = category_list.getProperty("CATEGORY_COUNT").toString(); 
        String SUPERTAG = category_list.getProperty("SUPERTAG").toString(); 
        String TYPE = category_list.getProperty("TYPE").toString(); 
        stringBuilder.append 
        (
         "Row value of: " +(i+1)+"\n"+ 
         "Category: "+CATEGORY+"\n"+ 
         "Category URL: "+CATEGORY_URL+"\n"+ 
         "Category_Icon: "+CATEGORY_ICON+"\n"+ 
         "Category_Count: "+CATEGORY_COUNT+"\n"+ 
         "SuperTag: "+SUPERTAG+"\n"+ 
         "Type: "+TYPE+"\n"+ 
         "******************************" 
        );     
        stringBuilder.append("\n"); 
       } 
      } 
+0

en el caso anterior, suponga que countryName = "" luego analiza su valor como anyType ... es decir. String countryName = anyType ... ¿Alguna solución para eso? –

+0

Ejemplo impresionante. – neteinstein

+0

@Rooban Ponraj Un ejemplo muy bueno pero con este código obteniendo solo el primer conjunto de respuestas como obtener solo ** libros ** respuesta de datos cada vez pero no obtener ** respuesta de datos de cámaras ** ... alguien puede por favor ayudarme. Gracias –

0

Mi Proyecto es trabajo Espero esto hepls.

 SoapObject requestx = new SoapObject(NAMESPACE, METHOD_NAME); 

     SoapSerializationEnvelope envelopex = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
     envelopex.dotNet = true; 
     envelopex.setOutputSoapObject(requestx); 
     HttpTransportSE httpTransportx = new HttpTransportSE(URL);   

     try {      
      httpTransportx.call(SOAP_ACTION, envelopex); 
      SoapObject responsex = (SoapObject)envelopex.getResponse(); // not envelopex.bodyIn; 

      int i=0; 
      int RCount=responsex.getPropertyCount(); 
      int[] tbIDArray = new int[RCount+1]; 
      int[] iMonthAarray = new int[RCount+1]; 
      int[] iYearAarray = new int[RCount+1]; 
      String[] sDetailAarray = new String[RCount+1]; 

      for (i = 0; i < RCount; i++) { 
       Object property = responsex.getProperty(i); 
       if (property instanceof SoapObject) { 
        SoapObject info = (SoapObject) property; 
        String tbID = info.getProperty("tbID").toString(); 
        String iMonth = info.getProperty("iMonth").toString(); 
        String iYear = info.getProperty("iYear").toString(); 
        String sDetail = info.getProperty("sDetail").toString(); 

        tbIDArray[i] =Integer.valueOf(tbID); 
        iMonthAarray[i] =Integer.valueOf(iMonth); 
        iYearAarray[i] =Integer.valueOf(iYear); 
        sDetailAarray[i] =sDetail; 
       }//if (property instanceof SoapObject) { 
      }//for (i = 0; i < RCount; i++) { 


     } catch (Exception exception) { 
      MsgBox1(exception.toString() , "Error"); 
     } 
0

El formato JSON es muy cómodo. Escribí un código simple para convertir la respuesta de SOAP V1 a JSON:

public static String soapStrToJson(String input) 
{ 
    String output; 

    output = input; 
    output = output.replace("key=", "\""); 
    output = output.replace("; value=", "\":"); 
    output = output.replace("; };",","); 
    output = output.replace("item=anyType{",""); 
    output = output.replace("Map",""); 
    output = output.replace(",}","}"); 
    output = output.replace(", }"," }"); 
    output = output.replace("null","0"); 

    Pattern pattern = Pattern.compile(":(.*?),"); 
    Matcher matcher = pattern.matcher(output); 

    List<String> wordsToReplace = new ArrayList(); 
    while (matcher.find()) 
    { 
     String str = matcher.group(0); 
     if(str.contains("{") || str.contains("[")) 
      continue; 

     str = str.replace(":", ""); 
     str = str.replace(",", ""); 

     if(str.matches("^-?\\d+$")) 
      continue; 

     System.out.println("-->" + str); 
     wordsToReplace.add(str); 
    } 

    for(String str : wordsToReplace) 
    { 
     output = output.replace(":"+str+",", ":\""+str+"\","); 
    } 
    return output; 
} 

y se utiliza esta función como:

parseCategoryJSON(new JSONObject(soapStrToJson(env.getResponse().toString()))) 

Tenga en cuenta que no estoy utilizando env.bodyIn SoapObject.

Puede que este no sea el convertidor perfecto para todas las respuestas, por lo tanto, modifique 'String.replace' y Pattern-Matchers según sus necesidades.

+0

Si esta pregunta es un duplicado de la pregunta enlazada, ciérrela como un duplicado en lugar de dejar una respuesta al respecto. Si no es un duplicado, deje una respuesta completa en lugar de una respuesta de solo enlace. – josliber