gpt4 book ai didi

java - Android JSON only OBJECT Fetching with Iteration

转载 作者:行者123 更新时间:2023-11-30 10:05:28 25 4
gpt4 key购买 nike

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

这是代码:我已经在我的 android studio 和 JSON 数据屏幕截图中尝试过 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;
}

最佳答案

这是一个完整的例子。适合我。

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();
}
}

关于java - Android JSON only OBJECT Fetching with Iteration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55256369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com