访问Json对象信息

时间:2014-03-21 05:35:25

标签: android json

我正在开发一个Android应用程序,因为我必须调用我的远程服务器,它会根据json对象给我数据。以下格式。

       {
-source: {
LS: " ABCDEF",
name: "XYXA",
point: "77.583859,12.928751"
},
 -stores: [
    -{
    ph: null,
    distance: "0.3",
    LS: " abcd",
    id: 1209,
    name: "xyz",
    point: "77.583835,12.926359"
    },
-{
    ph: null,
    distance: "0.3",
    LS: " abcd",
    id: 1209,
    name: "xyz",
    point: "77.583835,12.926359"
    }
    ]
}

我已经确认服务器正在给我回复。但是我没有得到如何在我的应用程序中访问这些数据。

任何人都可以给我一个访问这些数据的代码吗?

感谢你

2 个答案:

答案 0 :(得分:2)

                     JSONObject jsonObject=new JSONObject(responseString);
                     String LS=jsonObject.getJSONObject("source").get("LS").toString();
                     String name=jsonObject.getJSONObject("source").get("name").toString();
                     String point=jsonObject.getJSONObject("source").get("point").toString();
                     String[] latlng = point.split(",");
                     String lat=latlng[0];
                     String lng=latlng[1];
                     System.out.println("Lat "+lat+" Lng "+lng);
                     JSONArray jsonArray=jsonObject.getJSONArray("stores");
                     if (jsonArray.length()>0)
                     {
                        for (int i = 0; i < jsonArray.length(); i++) 
                        {
                             JSONObject jsonObject1=jsonArray.getJSONObject(i);
                             String ph=jsonObject1.get("ph").toString();
                             String distance=jsonObject1.get("distance").toString();
                             String LS=jsonObject1.get("LS").toString();
                             String id=jsonObject1.get("id").toString();
                             String name=jsonObject1.get("name").toString();
                             String point=jsonObject1.get("point").toString();
                             String[] latlng = point.split(",");
                             String lat=latlng[0];
                             String lng=latlng[1];
                             System.out.println("Lat "+lat+" Lng "+lng);
                        }
                    }

这是完整的解析代码部分。

答案 1 :(得分:0)

尝试解析您的JSON响应,如下所示:

JSONArray arra = new JSONArray("stores");
 for(int i=0;i<arra.length();i++)
  {
   JSONObject json = arra.getJSONObject(i);
   //Retrieve the data from the JSON object
   String name= json.getString("name");
   String points = json.getString("point");
   String loc=json.getString("LS");
}

<强>编辑:

从字符串点提取lat,你需要使用StringTokenizer分割字符串,如下所示:

   StringTokenizer stoken = new StringTokenizer(points, ",");
    while (stoken.hasMoreTokens()) {
           System.err.println(stoken.nextToken());
   }