2009-08-13 16 views
5

estoy usando KSOAP2 para llamar a un servicio web .NET desde la aplicación androide, y la respuesta del servicio web es el siguiente formatoCómo analizar esta respuesta del servicio web en Android?

anyType{ 
UserName=anyType{}; 
Password=anyType{}; 
ApplicationCode=JOB; 
ActionType=Query; 
MessageParameters=anyType{Parameters=anyType{}; }; 
TableData=anyType{TableNo=167; 
      TableName=Job; 
     DataRows= 
     anyType{ 
     DataRow= 
      anyType{ 
      DataRowValues= 
      anyType{ 
       DataRowValue= 
       anyType{ 
        FieldNo=1; 
        FieldName=No.; 
        PrimaryKey=true; 
        FieldType=Code20; DataValue=DEERFIELD, 8 WP; 
         }; 
       DataRowValue= 
       anyType 
         { 
        FieldNo=3; 
        FieldName=Description; 
        PrimaryKey=false; 
        FieldType=Text50; 
        DataValue=Setting up Eight Work Areas; 
         }; 
      DataRowValue= 
       anyType 
         { 
        FieldNo=4; 
        FieldName=Description 2; 
        PrimaryKey=false; 
        FieldType=Text50; 
        DataValue=anyType{}; 
         }; 
       }; 
       }; 
      }; 
     }; 
    }; 
ResponseForRequest=GETTABLEDATA; 
CustomIdentifier=TestBB; 
Applications=anyType{}; 
Forms=anyType{}; 
Menu=anyType{}; 
} 

No estoy al tanto sobre el formato de esta respuesta y no me Sepa cómo analizar esta respuesta para obtener un resultado particular. Cualquiera que sepa al respecto, por favor, ayúdeme.

Nota: He formateado manualmente esta respuesta para su comprensión.

Respuesta

7

En realidad, este es un formato conocido si conoce Java Script. Estos datos en este formato son de hecho JSON Object y JSON Array. Espero que estés usando el KSOAP2 library. Así es como puedes analizar este resultado.

por ejemplo:

private Bundle bundleResult=new Bundle(); 
private JSONObject JSONObj; 
private JSONArray JSONArr; 
Private SoapObject resultSOAP = (SoapObject) envelope.getResponse(); 
/* gets our result in JSON String */ 
private String ResultObject = resultSOAP.getProperty(0).toString(); 

if (ResultObject.startsWith("{")) { // if JSON string is an object 
    JSONObj = new JSONObject(ResultObject); 
    Iterator<String> itr = JSONObj.keys(); 
    while (itr.hasNext()) { 
     String Key = (String) itr.next(); 
     String Value = JSONObj.getString(Key); 
     bundleResult.putString(Key, Value); 
     // System.out.println(bundleResult.getString(Key)); 
    } 
} else if (ResultObject.startsWith("[")) { // if JSON string is an array 
    JSONArr = new JSONArray(ResultObject); 
    System.out.println("length" + JSONArr.length()); 
    for (int i = 0; i < JSONArr.length(); i++) { 
     JSONObj = (JSONObject) JSONArr.get(i); 
     bundleResult.putString(String.valueOf(i), JSONObj.toString()); 
     // System.out.println(bundleResult.getString(i)); 
    } 
} 

Inicialmente yo tenía un montón de problemas con este tipo de datos, pero finalmente lo tengo todo working.From entonces he estado usando this.I esperanza esto ayuda a resolver su problema.

+0

cómo obtener el resultado de ese método de análisis en mi declaración de devolución? – blankon91

+0

Ahora obtendrá el formato del resultado en el formato de {clave1: val1, clave2: val2, ......} que se almacenan en un paquete, así que devuelva 'paqueteResult' – 1HaKr

+0

bien, gracias :) – blankon91

0

No reconozco el formato. Creo que tendrá que analizar la respuesta usted mismo,

Una serie de expresiones regulares parece ser el inicio más rápido.

por ejemplo:

String intput = ""; //your big response string 
List<Map<String,String>> rows = new ArrayList<Map<String,String>>(); 
String[] rowdata = input.matches("DataRowValue\=\r\s*anyType{[^}]*};"); 


for (String r : rowdata){ 
    Map<String, String> row = new HashMap<String, String>(); 
    String[] nvpairs = r.split(";"); 

    for (string pair : nvpairs) { 
     String[] s = pair.split("="); 
     row.push(s[0], s[1]); 
    } 

} 

debe empezar. Es probable que necesite ajustar la primera expresión regular por muchas razones. algo así como "(? < = DataRowValue = [^ {] ) [^}]" podría ser más apropiado. estaría tentado a acceder a cualquier cosa que sólo aparece una vez por la pesca a cabo directamente con algo así como

cadena usuario = input.match ("(< = Usuario \ =)? [^;] *")

3

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 hacer el análisis sintáctico de esta manera:

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"); 
       } 
      } 
5

Siempre que la respuesta SOAP está en un formato JSON válida; la respuesta aceptada puede no siempre ser exitosa, ya que la cadena de respuestas no comienza con "{" sino con "anyType".

En este caso, siempre recibí un error con respecto a "anyType" no siendo un objeto JSON válido. Luego procedí a subscribir la cadena de respuesta con IndexOf ("{"); y esto luego comenzó el análisis, aunque nuevamente si la cadena de respuesta no es un formato JSON válido, se romperá.

El problema aquí era que mi cadena de respuestas tenía caracteres no escapados que no funcionaban bien con el formato JSON.

Con referencia a esta respuesta: Android KSoap2: how to get property name

esto es lo que he conseguido poner en práctica:

public Bundle getElementsFromSOAP(SoapObject so){ 
    Bundle resultBundle = new Bundle(); 
    String Key = null; 
    String Value = null; 
    int elementCount = so.getPropertyCount();     

    for(int i = 0;i<elementCount;i++){ 
     PropertyInfo pi = new PropertyInfo(); 
     SoapObject nestedSO = (SoapObject)so.getProperty(i); 

     int nestedElementCount = nestedSO.getPropertyCount(); 
     Log.i(tag, Integer.toString(nestedElementCount)); 

     for(int ii = 0;ii<nestedElementCount;ii++){ 
      nestedSO.getPropertyInfo(ii, pi); 
      resultBundle.putString(pi.name, pi.getValue().toString()); 
      //Log.i(tag,pi.getName() + " " + pii.getProperty(ii).toString()); 
      //Log.i(tag,pi.getName() + ": " + pi.getValue()); 

     } 
    } 

    return resultBundle; 

} 
+0

Hola, ¿solucionó esto el problema? – Solace

+0

@Zarah No estoy seguro de lo que hace la pregunta que publicó. Puede proporcionar más detalles al respecto. – ramizmoh

+0

Gracias por la respuesta. Usé su método, pero la cadena de datos completa se devuelve desde el servicio web como una propiedad (propertyCount es 1). En segundo lugar, mi cadena de respuestas no puede validarse en los analizadores JSON en línea, por lo que creo que mis datos no están en un formato JSON válido. Publiqué una [pregunta aquí] (http://stackoverflow.com/questions/24268924/weird-soap-response-is-it-json-how-to-parse-it). Entonces, ¿puede sugerirme cuál será una forma adecuada de analizar esa respuesta desde un servicio web? – Solace

0

respuesta SoapObject = (SoapObject) envelope.getResponse();

  int cols = response.getPropertyCount(); 

      for (int i = 0; i < cols; i++) { 
       Object objectResponse = (Object) response.getProperty(i); 




       SoapObject r =(SoapObject) objectResponse; 

       FieldName=(String) r.getProperty("FieldName").toString(); 

       // Get the rest of your Properties by 
       // (String) r.getProperty("PropertyName").toString(); 

      } 
Cuestiones relacionadas