Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse this Web service response in Android?

Tags:

android

I am using KSOAP2 to call a .NET webservice from android application,and the response from the web service is in the following format

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

I am not aware about the format of this response and i don't know how to parse this response to get particular result.Any one knows about it please help me.

Note: i manually formatted this response for your understanding.

like image 978
Rajapandian Avatar asked Aug 13 '09 05:08

Rajapandian


3 Answers

Actually this a known format if you know Java Script.These data in this format are infact JSON Object's and JSON Array's. I hope you are using the KSOAP2 library.So here is how you can parse this result.

eg:

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

Initially i had a lot of trouble with this kind of data but finally i got it all working.From then I have been using this.I hope this helps you solve your problem.

like image 160
1HaKr Avatar answered Oct 14 '22 12:10

1HaKr


Provided that the SOAP response is in a valid JSON format; the accepted answer may not always be successful, as the the response string does not start with "{" but with "anyType".

In this case, I always got an error regarding "anyType" not being a valid JSON Object. I then proceeded to substring the response string with the IndexOf("{"); and this then started the parsing, though again if the response string is not a valid JSON format, it will break.

The issue here was that my response string had un-escaped characters which did not play nicely with the JSON formatting.

With reference to this answer: Android KSoap2: how to get property name

this is what I managed to implement:

    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;

}
like image 37
ramizmoh Avatar answered Oct 14 '22 13:10

ramizmoh


For example your Response:

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

For requesting and parsing do like this:

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");
               }
           }
like image 3
Rooban Ponraj A Avatar answered Oct 14 '22 12:10

Rooban Ponraj A