如何在android开发中解析从web服务返回的ksoap2响应?

时间:2012-03-27 21:49:23

标签: android xml-parsing android-ksoap2

调用Web方法后,将返回XML字符串作为响应。 android端代码是这样的:

SoapPrimitive response = (SoapPrimitive) ws.envelope.getResponse();

,xml就像:

<string xmlns="http://tempuri.org/">
[{"ID":"leo@gmail.com","float_latitude":22.338,"float_longitude":114.169},          {"ID":"emmy@emmy.com","float_latitude":22.33974,"float_longitude":114.169456},    {"ID":"bob@bob.com","float_latitude":22.3384857,"float_longitude":114.1691},    {"ID":"kay@kay.com","float_latitude":50,"float_longitude":100}]
</string>

我想要

  1. 返回的ID数
  2. 将关于id的lat和long保存到我的本地变量

1 个答案:

答案 0 :(得分:2)

噢,伙计。首先,您的响应不是XML,而是JSON。我解析JSON的方法是首先构建一个通用对象。

 public class yourObject{

  private String id; 
  private double lat;
  private double lng; 
 }

从那里建立一个集合,一个arraylist应该没问题。

  ArrayList<yourObject> objects = new ArrayList<yourObject>(); 

之后,对JSON进行一些研究是一些初学者代码。

 JSONArray myAwarry = new JSONArray(response);

传入从服务器返回的字符串,例如响应。

遍历数组

 for(int i = 0; i < myAwarry.length(); i++){
 JSONObject o = myAwarry.get(i); 
 yourObject obj = new yourObject(); 
 obj.setId(o.getString("ID")); 
 obj.setlat(o.getDouble("float_longitude")); 
 obj.setlng(o.getDouble("float_latitude")); 
 //add the obj to the collections of objects
  objects.add(obj); 

}

希望这有帮助