gpt4 book ai didi

java - 输出解析后的Json数据

转载 作者:行者123 更新时间:2023-12-01 20:25:05 25 4
gpt4 key购买 nike

所以我有一个已经解析过的Json文件,我想知道如何将Json文件中的信息显示到屏幕上?这是Json的解析。

public String loadJSONFromAsset()
{
String json = null;
try
{
InputStream is = getAssets().open("JSON.json");

int size = is.available();

byte[] buffer = new byte[size];

is.read(buffer);
is.close();

json = new String(buffer, "UTF-8");
}
catch(IOException ex)
{
ex.printStackTrace();
return null;
}
return json;
}

JSON:

{"answers":[
{
"answer": "1"
},
{
"answer": "2"
},
{
"answer": "3"
},
{
"answer": "4"
},
{
"answer": "5"
}
]}

如何将“4”等输入到变量中?我希望我的问题足够清楚,如果不够清楚,请发表评论。我想做的只是输出其中一个数字。

最佳答案

使用此示例代码希望它能解决您的问题

 private void parseJson(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("answers");
for (int i = 0; i < jsonArray.length(); i++){
String answer = jsonArray.getJSONObject(i).getString("answer");
Log.i(TAG,"answer: "+answer);
}
} catch (Exception e) {
e.printStackTrace();
}

}

关于java - 输出解析后的Json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43978690/

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