简体   繁体   English

解析ksoap2响应

[英]Parsing ksoap2 response

I use a ksoap2 lib for communicating from android client with SOAP web service. 我使用kso​​ap2 lib从android客户端与SOAP Web服务进行通信。 Great job was done by ksoap team, but the problem is, there is no any good example how to use it correct in different aspects. ksoap团队做的很棒,但是问题是,没有一个很好的例子说明如何在不同方面正确使用它。 For instance I get in soap response following data: 例如,我得到以下数据的肥皂响应:

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

It's a complex object, or rather a collection of StatusSetting objects. 它是一个复杂的对象,或者是StatusSetting对象的集合。 When I try to get a property of SoapObject it's only 1 property with all that data as a string. 当我尝试获取SoapObject的属性时,只有1个属性,其中所有数据均为字符串。 It can't be parsed as json too. 它也不能解析为json。 Unbelievable that nobody met same problem regarding to popularity android is gaining. 令人难以置信的是,没有人遇到过关于流行性android的相同问题。 Would be very cool to know if somebody solved this issue and how. 知道是否有人解决了这个问题以及如何解决将非常酷。 Thanks. 谢谢。

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

Hope it should work 希望它能工作

Here is a tutorial on how to work with array of complex objects with KSOAP . 这是有关如何使用KSOAP处理复杂对象数组的教程 I found out by countless hours of debugging. 我发现了无数小时的调试。 Hope this hepls 希望这个帮助

My Project it's work. 我的项目正常。 Hope this 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");
        }

JSON format is much comfortable. JSON格式非常舒适。 I wrote a simple code to convert SOAP V1 response to JSON: 我编写了一个简单的代码将SOAP V1响应转换为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;
}

and used this function as: 并将此函数用作:

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

Note that I am not using env.bodyIn SoapObject. 请注意,我没有使用env.bodyIn SoapObject。

This may not be the perfect converter for all responses, so modify 'String.replace' and Pattern-Matchers as per your requirement. 这可能不是所有响应的理想转换器,因此请根据您的要求修改'String.replace'和Pattern-Matchers。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM