仅适用于Android JSON的带有迭代的对象提取

时间:2019-03-20 08:26:53

标签: java android json parsing

我有一个仅包含对象的json文件,现在我无法通过迭代获取所有对象,因为这里没有数组。

这是代码:我在android studio和JSon Data屏幕截图enter image description here中尝试过的

  @Override
    protected String doInBackground(String... strings) {
        try {
            url = new URL("https://api.myjson.com/bins/r7dj6");
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.connect();
            inputStream = httpURLConnection.getInputStream();

           bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
           String line =" ";

           while ((line = bufferedReader.readLine()) != null){
               stringBuffer.append(line);

           }

           String fullfile = stringBuffer.toString();

            JSONObject jsonObject = new JSONObject(fullfile);
            JSONObject jsonObjectchild = jsonObject.getJSONObject("Apartment");




        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }


        return null;
    }

2 个答案:

答案 0 :(得分:1)

这是一个完整的示例。为我工作。

HttpURLConnection connection = null;
try {
    URL url = new URL("https://api.myjson.com/bins/r7dj6");
    connection = (HttpURLConnection) url.openConnection();
    connection.connect();
    InputStream inputStream = connection.getInputStream();

    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    String line;
    StringBuilder stringBuffer = new StringBuilder();
    while ((line = reader.readLine()) != null){
        stringBuffer.append(line);
    }

    JSONObject jsonObject = new JSONObject(stringBuffer.toString());
    JSONObject apartmentObject = jsonObject.getJSONObject("Apartment");
    Iterator<String> keys = apartmentObject.keys();
    while (keys.hasNext()) {
        String flatName = keys.next();
        JSONObject flat = apartmentObject.getJSONObject(flatName);
        String age = flat.getString("age");
        String color = flat.getString("color");
        String name = flat.getString("name");
        String owner = flat.getString("owner");
        String partner = flat.getString("partner");
        Log.d("Flat", flatName + ": " + age + ", " + color + ", " + name + ", " + owner + ", " + partner);
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (connection != null) {
        connection.disconnect();
    }
}

答案 1 :(得分:0)

您仍然可以迭代:

for (Iterator key=jsonObjectchild.keys();key.hasNext();) {
    JSONObject flatName = json.get(key.next());
    ...
}