如何提取JSON文件的特定部分?

时间:2019-02-10 11:35:00

标签: java android json

这是我的JSON文件:

  {  
     "coord":{  
        "lon":139,
        "lat":35
     },
     "weather":[  
        {  
           "id":803,
           "main":"Clouds",
           "description":"broken clouds",
           "icon":"https://cdn.glitch.com/6e8889e5-7a72-48f0-a061-863548450de5%2F04n.png?1499366020983"
        }
     ],
     "base":"stations",
     "main":{  
        "temp":7,
        "pressure":1025,
        "humidity":75,
        "temp_min":7,
        "temp_max":7
     },
     "visibility":10000,
     "wind":{  
        "speed":5.1,
        "deg":100
     },
     "clouds":{  
        "all":75
     },
     "dt":1549794600,
     "sys":{  
        "type":1,
        "id":8024,
        "message":0.0034,
        "country":"JP",
        "sunrise":1549748122,
        "sunset":1549786891
     },
     "id":1851632,
     "name":"Shuzenji",
     "cod":200
  }

我尝试提取weather数组,但是不起作用。

        JSONArray mArray;
        try {
            mArray = new JSONArray(result);
            for (int i = 0; i < mArray.length(); i++) {
                JSONObject mJsonObject = mArray.getJSONObject(i);
                txtJson.append(mJsonObject.getString("weather"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
            //txtJson.setText(result);
        }

        txtJson.setText(result);
    }

1 个答案:

答案 0 :(得分:0)

我不知道您希望该代码做什么,但是如果您要提取天气数组,这就是您的方法。

JSONObject json = new JSONObject(result);
JSONArray weather = json.getJSONArray("weather");

然后您可以在数组中获取单个条目

JSONObject entry = weather.getJSONObject(0);
int id = entry.getInt("id");
String main = entry.getString("main");

或者如果您只是想将数组转回字符串

String s = weather.toString();