How to parse this Web service response in Android?
Asked Answered
L

4

5

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.

Langlois answered 13/8, 2009 at 5:35 Comment(0)
F
7

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.

Frisby answered 12/1, 2010 at 13:16 Comment(2)
how to get the result from that parsing method into my return statement?Sapor
Now you will get the format the result in the format of {key1:val1, key2:val2,......} which are stored in a bundle ,so return 'bundleResult'Frisby
C
5

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;

}
Clientage answered 11/12, 2012 at 12:6 Comment(4)
@Zarah I am not sure what you are asking by the question you posted. Can you provide further detail in this regard.Clientage
Thanks for the response. I used your method but the entire data string is returned from the web service as one property (the propertyCount is 1). Secondly my response string fails to validate in online JSON parsers, so I think my data is not in a valid JSON format. I posted a question here. So can you suggest me what will be a suitable way to parse such a response from a webservice?Allocation
@Zarah: As mentioned in your linked question, the solution posted here has worked to a certain extent and should be used as a basis to understand how KSOAP maps the web service response. With this in mind, you should use this code sample to identify each anyType element and map\cast it as an Object. Then for each anyType element that you mapped\cast as an Object; check if it is of class Soap and do a property count and follow the same process for the anyType elements in this regard. For objects not of class type Soap (key1:value1), retrieve this as getPropertyAsString from the main soap objectClientage
@Zarah: propertyCount=1 because the web service string (response) is a soap object. Cast your string as a soap object and then do a propertyCount, which will return 3. One of these properties (key3=anyType) is another soap object and should be cast as such.Clientage
C
0

I dont recognise the format. I think you are going to have to parse the reponse yourself,

A series of regex's seems the quickest start.

eg:

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

}

should get you started. You will probably need to adjsut the first regex for lots of reasons. something like "(?<=DataRowValue=[^{])[^}]" might be more approriate. I'd be tempted to access anything that only appears once by fishing it out directly with something like

String username = input.match("(?<=UserName\=)[^;]*")

Cissoid answered 13/8, 2009 at 13:30 Comment(0)
N
0

SoapObject response = (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();

            }
Nidify answered 28/8, 2014 at 8:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.