2012-02-15 2 views
0

В моем случае у меня есть ответ на мыло, в котором хранятся значения значений «ArrayOfArrayOfString».Как преобразовать мыльный отклик в многомерный массив?

Это похоже на массив A [4] [4].

А [0] [0] -> ServiceId

А [0] [1] -> Имя_службы

А [0] [2] -> ServiceImageURL

А [0] [3] -> ServiceDecription

а [0] [4] -> ServiceIconURL

и все его же Шифрование до а [4] [4].

Как я могу обработать этот тип ответа в андроиде?

код что-то вроде:

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);   

     SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
     envelope.dotNet = true; 

     envelope.setOutputSoapObject(request); 

     HttpTransportSE transportSE = new HttpTransportSE(URL); 
     transportSE.debug = true; 

              Log.i("WebService", "msg:try_out"); 
    String[] columns = null; 

    ArrayList<String> rows = new ArrayList<String>(); 

    try 
    { 
                Log.i("WebService", "msg:try+in"); 
     transportSE.call(SOAP_ACTION, envelope);        
                Log.i("WebService", "msg:SoapObject"); 


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

                Log.i("WebService", "Response"); 

try 
      { 
       // WhaT SHOULD I USE HERE to convert it to 2D Array// 
      } 
      catch (Exception e) 
      { 
       e.printStackTrace(); 
       Log.v("CATCH BLOCK", e.getMessage()); 
      } 
} 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
      Log.i("WebService", "msg:Exception error"); 
      Log.i("WebSerivce", e.getMessage()); 
      return e.getMessage(); 
     } 

Пожалуйста, помогите мне об этом.

+0

Вот мыло-код ::: – Harpreet

+0

Ведущий: www.xyz.com Content-Type: Текст/XML; кодировка = UTF-8 Content-Length: длина SOAPAction: "http://abc.net/webservices/LoadServices" <мыло: Envelope xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd = "http://www.w3.org/2001/XMLSchema" xmlns: soap = "http: // schemas.xmlsoap.org/soap/envelope/"> Harpreet

+0

строка строка строка строка Harpreet

ответ

3

Это идеальный рабочий код для разбора сложных данных ...

Я только делаю это для A [0] [1-4] и в соответствии с моим ответом мыльного изменить код в соответствии с урами мыла ответ.

SoapObject result = (SoapObject)enevlop.getResponse(); 

      String str = result.getProperty(0).toString(); 
      // add a for loop for ur code and iterate it according to ur soap response and get all the node using getProperty(i); 

      String str1 = lameParser(str); 

      textView.setText(""+str1); 

Теперь определит метод lameParser(): -

public String lameParser(String input){ 

    String sName=input.substring(input.indexOf("sName=")+6, input.indexOf(";", input.indexOf("sName="))); 

    int IGoals=Integer.valueOf(input.substring(input.indexOf("iGoals=")+7, input.indexOf(";", input.indexOf("iGoals=")))); 

    String sCountry=input.substring(input.indexOf("sCountry=")+9, input.indexOf(";", input.indexOf("sCountry="))); 

    String sFlag=input.substring(input.indexOf("sFlag=")+6, input.indexOf(";", input.indexOf("sFlag="))); 

    return sName+"\n"+Integer.toString(IGoals)+"\n"+sCountry+"\n"+sFlag; 
} 
+0

Hi Himanshu, Спасибо за ваш ответ. Но так или иначе, я могу сохранить результат непосредственно в двухмерном массиве? – Harpreet

+0

Я пытался использовать ваш код. У меня была проблема, что перед каждым значением у меня есть «string =», поэтому его просто выбирает A [0] [0] каждый раз. Вот моментальный снимок реального полного ответа. https://885427425446120200-a-1802744773732722657-s-sites.googlegroups.com/site/harryb87/scrnpng – Harpreet

+0

Проверьте моментальный снимок. Я получаю ответ «string = 922», тогда как мне просто нужно «922». Этот ответ повторяется для каждого поля, которое я указываю, поскольку нет другой вещи для указания, а не: input.indexOf ("string =") :( – Harpreet

1

Вот код для разбора несколько дочернего узла данных XML ...

public static void parseBusinessObject(String input, Object output) throws NumberFormatException, IllegalArgumentException, IllegalAccessException, InstantiationException{ 

     Class theClass = output.getClass(); 
     Field[] fields = theClass.getDeclaredFields(); 

     for (int i = 0; i < fields.length; i++) { 
      Type type=fields[i].getType(); 
      fields[i].setAccessible(true); 

      //detect String 
      if (fields[i].getType().equals(String.class)) { 
       String tag = "s" + fields[i].getName() + "="; //"s" is for String in the above soap response example + field name for example Name = "sName" 
       if(input.contains(tag)){ 
        String strValue = input.substring(input.indexOf(tag)+tag.length(), input.indexOf(";", input.indexOf(tag))); 
        if(strValue.length()!=0){ 
         fields[i].set(output, strValue); 
        } 
       } 
      } 

      //detect int or Integer 
      if (type.equals(Integer.TYPE) || type.equals(Integer.class)) { 
       String tag = "i" + fields[i].getName() + "="; //"i" is for Integer or int in the above soap response example+ field name for example Goals = "iGoals" 
       if(input.contains(tag)){ 
        String strValue = input.substring(input.indexOf(tag)+tag.length(), input.indexOf(";", input.indexOf(tag))); 
        if(strValue.length()!=0){ 
         fields[i].setInt(output, Integer.valueOf(strValue)); 
        } 
       } 
      } 

      //detect float or Float 
      if (type.equals(Float.TYPE) || type.equals(Float.class)) { 
       String tag = "f" + fields[i].getName() + "="; 
       if(input.contains(tag)){ 
        String strValue = input.substring(input.indexOf(tag)+tag.length(), input.indexOf(";", input.indexOf(tag))); 
        if(strValue.length()!=0){ 
         fields[i].setFloat(output, Float.valueOf(strValue)); 
        } 
       } 
      } 
     } 

    } 

Если вам понравится этот пост дать мне чтобы посетители легко находили его ...

+0

Спасибо за помощь. – Harpreet

+0

проблема ур решена этим ответом ??? – himanshu

+0

Я работаю над этим. – Harpreet

1
try 
{ 
     Log.i("WebService", "Try Block"); 
     transportSE.call(SOAP_ACTION, envelope);       
     Log.i("WebService", "msg:SoapObject"); 

     SoapObject response = (SoapObject)envelope.getResponse(); 
     Log.i("WebService", "Response on"); 
     int totalService = response.getPropertyCount(); 

     int i; 
     String str ; 
     String str1; 

     for (i = 0; i < totalService; i++) 
     { 
     str = response.getProperty(i).toString(); 
      Log.i("WebService", "ForLoop "+ Integer.toString(i)); 
     str1 = lameParser(str, i); 
      Log.i("WebService", "ForLoop: lameParser done"); 
      Log.i("WebService", "Value Stored:: "+ str1); 
     } 
     }            
     catch (Exception e) 
     { 
      e.printStackTrace(); 
      Log.i("WebService", "msg:Exception error"); 
      Log.i("WebSerivce", e.getMessage()); 

     }     

    } 



    private String lameParser(String input, int I) 
    { 
     int i = I; 
     Log.i("WebService", "LameParse()"); 
    try 
    { 
    String SId = input.substring(input.indexOf("{string=")+8, input.indexOf(";", input.indexOf("{string="))); 
     String SName = input.substring(input.indexOf(" string=")+8, input.indexOf(";", input.indexOf(" string="))); 
     String SIurl = input.substring(input.indexOf("http"), input.indexOf(";", input.indexOf("http"))); 
     String SIcon = input.substring(input.indexOf("jpg; string=")+12, input.indexOf("; }", input.indexOf("jpg; string="))); 

     // String[][] arr = new String[x][y]; is already initialized as local var of class. 
     arr[i][0] = SId; 
     arr[i][1] = SName; 
     arr[i][2] = SIurl; 
     arr[i][3] = SIcon; 



     return SId + "\n" + SName + "\n" + SIurl + "\n" + SIcon + "\n" ; 

     } 
     catch (Exception e) 
     { 
      Log.i("WebService", "catch exception"); 
      Log.i("WebService", e.getMessage()); 
      return null; 
     } 
    } 
1

Вот как я обработал объекты ArrayOfArrayOfString.

SoapObject result = (SoapObject)envelope.bodyIn; 
if (result.getPropertyCount() > 0) { 
    SoapObject Rows = (SoapObject)result.getProperty(0); 
    int nRows = Rows.getPropertyCount(); 
    for (int nRow=0; nRow<nRows; nRow++) { 
     SoapObject Cols = (SoapObject)Rows.getProperty(nRow); 
     int nCols = Cols.getPropertyCount(); 
     for (int nCol=0; nCol<nCols; nCol++) { 
      String sCol = Cols.getProperty(nCol).toString(); 

      // Process sCol with nRow and nCol as array indexes 
     } 
    } 
} 
Смежные вопросы