在Android中解析JSON响应

5

我正在为Android编写一个HTTP GET请求,用于查询Foursquare API附近的活动。我收到的JSON响应是:

{"groups": [
{
  "type": "Nearby",
  "venues": [
    {
      "id": 2587838,
      "name": "Marriott Druids Glen Hotel Newtownmountkennedy",
      "primarycategory": {
        "id": 79281,
        "fullpathname": "Travel:Resort",
        "nodename": "Resort",
        "iconurl": "http://foursquare.com/img/categories/travel/resort.png"
      },
      "address": "Newtownmountkennedy",
      "city": "Newtownmountkennedy",
      "state": "",
      "verified": false,
      "geolat": 53.091717,
      "geolong": -6.079162,
      "stats": {
        "herenow": "0"
      },
      "distance": 5596
    },

这些场馆可能有很多个。使用以下代码,我可以将场馆信息打印出来:

InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
Log.i("Hoosheer0",result);

// A Simple JSONObject Creation
JSONObject json=new JSONObject(result);
JSONArray venues = json.getJSONArray("groups");
//JSONArray docsArray = jObject.getJSONArray("docs");
for (int i = 0; i<venues.length();i++){
    String name = venues.getJSONObject(i).optString("venues");
    //String venueName = name.
    Log.i("This is a name... pleasse", name);
}

instream.close();

我该如何获取地理纬度和经度的值?

2个回答

12

我相信将这段代码放在你的for循环中应该能解决问题:

JSONObject venueObject = venues.getJSONObject(i);
double geoLat = venueObject.getDouble("geolat");
double geoLong = venueObject.getDouble("geolong");

这返回一个错误 "没有geolat的值"。这是因为它在场馆内吗? - Stina
@Christina:嗯,是的,“geolat”确实在场馆内(根据您的示例)。这就是为什么在我的代码中,我首先从“JSONArray venues”获取一个表示场馆的单个“JSONObject”,然后从“venueObject”获取纬度和经度。确保拼写正确,并在调试器中逐步执行代码以更详细地检查“venueObject”的值。 - Julian
刚注意到括号未被复制。我认为这就是为什么它不允许我访问地理纬度的原因?我现在已经编辑了问题。感谢帮助。 - Stina

0

您可以在这里查看并选择一个JSON库来获取这些值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接