无法使用GSON解析JSONArray

时间:2014-06-23 10:46:52

标签: java android json gson

我在开发Android应用程序时遇到了问题。我的问题是我不知道如何使用GSON从URL解析JSON代码。我搜索谷歌和SO大约一个小时左右,但没有任何对我有用。我在互联网上找到的所有东西都引用了自定义JSON代码,而不是来自URL的代码。这是我的数据的一小部分样本。

  {
    "status": {
        "error": "NO",
        "code": 200,
        "description": "none",
        "message": "Request ok"
    },
    "geoLocation": {
        "city_id": "147",
        "city_long": "Saint-Laurent",
        "region_short": "QC",
        "region_long": "Quebec",
        "country_long": "Canada",
        "country_id": "43",
        "region_id": "35"
    },
    "stations": [
        {
            "country": "Canada",
            "price": "3.65",
            "address": "3885, Boulevard Saint-Rose",
            "diesel": "0",
            "id": "33862",
            "lat": "45.492367",
            "lng": "-73.710915",
            "station": "Shell",
            "region": "Quebec",
            "city": "Saint-Laurent",
            "date": "3 hours agp",
            "distance": "1.9km"
        },
        {
            "country": "Canada",
            "price": "3.67",
            "address": "3885, Saint-Mary",
            "diesel": "0",
            "id": "33872",
            "lat": "45.492907",
            "lng": "-73.740715",
            "station": "Shell",
            "region": "Quebec",
            "city": "Saint-Laurent",
            "date": "3 hours agp",
            "distance": "2.0km"
        }
    ]
}

我是JSON / GSON的初学者,所以我需要一些帮助。这就是我所拥有的:

try {
            String sURL = "http://api.mygasfeed.com/stations/radius/(39.631439)/(-80.8005451)/(25)/reg/(price)/uc82wk25m0.json?callback=?";
            URL url = new URL(sURL);
            HttpURLConnection request = (HttpURLConnection) url.openConnection();
            request.connect();

            // Convert to a JSON object to print data
            JsonParser jp = new JsonParser(); //from gson
            JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //convert the input stream to a json element
            JsonObject rootobj = root.getAsJsonObject(); //may be an array, may be an object.
            longitude = rootobj.get("price").getAsString();
            latitude = rootobj.get("address").getAsString();
        } catch (Exception e) {
            e.printStackTrace();
        }

我尝试了一个解析数组的循环但是失败了。任何有关此问题的帮助都非常感谢。

------------------------------ EDIT ------------- ---------------------------------- 对于不正确的JSON代码,我感到非常抱歉。我已经更新了代码,但仍然无法找到解决方案。

3 个答案:

答案 0 :(得分:1)

你JSON错了:

   "date": "3 hours agp",
    "distance": "1.9km"
}
{
    "country": "Canada",

要更正它,您必须添加,

  "date": "3 hours agp",
    "distance": "1.9km"
},
{
    "country": "Canada",

答案 1 :(得分:0)

试试这个,使用基本的 org.json.JSONObject org.json.JSONArray 它对我来说很好......

// This string is the JSON you gave as imput
String json = "{ \"status\": {  \"error\": \"NO\",  \"code\": 200,  \"description\": \"none\",  \"message\": \"Request ok\" }, \"geoLocation\": {  \"city_id\": \"147\",  \"city_long\": \"Saint-Laurent\",  \"region_short\": \"QC\",  \"region_long\": \"Quebec\",  \"country_long\": \"Canada\",  \"country_id\": \"43\",  \"region_id\": \"35\" }, \"stations\": [  {\"country\": \"Canada\",\"price\": \"3.65\",\"address\": \"3885, Boulevard Saint-Rose\",\"diesel\": \"0\",\"id\": \"33862\",\"lat\": \"45.492367\",\"lng\": \"-73.710915\",\"station\": \"Shell\",\"region\": \"Quebec\",\"city\": \"Saint-Laurent\",\"date\": \"3 hours agp\",\"distance\": \"1.9km\"  },  {\"country\": \"Canada\",\"price\": \"3.67\",\"address\": \"3885, Saint-Mary\",\"diesel\": \"0\",\"id\": \"33872\",\"lat\": \"45.492907\",\"lng\": \"-73.740715\",\"station\": \"Shell\",\"region\": \"Quebec\",\"city\": \"Saint-Laurent\",\"date\": \"3 hours agp\",\"distance\": \"2.0km\"  } ]}";

try{
    JSONObject rootobj = new JSONObject(json);
    JSONArray array = rootobj.getJSONArray("stations");
    for( int i = 0; i < array.length(); i++){
        JSONObject o = array.getJSONObject(i);
        String price = o.getString("price");
        String address = o.getString("address");
        //...

    }
}catch(JSONException jse){
    // Manage Exception here
}

答案 2 :(得分:0)

尝试以下代码从url获取数据并使用Gson解析响应。

注意:删除&#34;?callback =?&#34;从您的网址中删除&#34;?(&#34;来自您的回复

try {
    String sURL = "http://api.mygasfeed.com/stations/radius/(39.631439)/(-80.8005451)/(25)/reg/(price)/uc82wk25m0.json";

    URL u = new URL(sURL);
    HttpURLConnection request = (HttpURLConnection) u.openConnection();
    request.setRequestMethod("GET");
    request.connect();
    int status = request.getResponseCode();

    switch (status) {
        case 200:
        case 201:
            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));

            JsonElement element = new Gson().fromJson (br, JsonElement.class);
            JsonObject jsonObj = element.getAsJsonObject();

            JsonArray jArray = jsonObj.get("stations").getAsJsonArray();

            for (int i = 0, size = jArray.length(); i < size; i++) {

               JSONObject jObj = jArray.getJSONObject(i);

               System.out.println(" Price : " + jObj.get("price").toString());
               System.out.println(" Address : " + jObj.get("address").toString());
            }
    }

} catch (MalformedURLException ex) {
    // Manage Exception here
} catch (IOException ex) {
    // Manage Exception here
}