gpt4 book ai didi

Java JSON 从 JSONArray 的 JSONObject 中的选定名称中提取值

转载 作者:行者123 更新时间:2023-11-29 06:45:22 28 4
gpt4 key购买 nike

我正在尝试从 JSONArray 创建的 JSONbject 中的名称中提取值,JSONAarray 是从主(根)JSONObject 创建的。

这是 JSON:

{"filelist": [{
"1": {
"filename": "sample.mp3",
"baseurl": "http://etc.com/"
}}]}

我相当确定 JSON 格式正确。

这是 Java(对于 Android SDK,这是在主 Activity 类的 OnCreate 方法中):

    String jsonString = new String("{\"filelist\": [{ \"1\": { \"filename\": \"sample.mp3\", \"baseurl\": \"http://etc.com/\" }}]}");
JSONObject jObj = new JSONObject(jsonString);
JSONArray jArr = new JSONArray(jObj.getJSONArray("filelist").toString());
JSONObject jSubObj = new JSONObject(jArr.getJSONObject(0).toString());
textView1.setText(jSubObj.getString("filename"));

感谢您的浏览,非常感谢任何答案。

最佳答案

您可能希望简化 JSON 结构,但您现在可以按如下方式阅读它:

JSONObject jObj;
try {
jObj = new JSONObject(jsonString);
JSONArray jArr = jObj.getJSONArray("filelist");
JSONObject jObj2 = jArr.getJSONObject(0);
textView1.setText(jObj2.getJSONObject("1").getString("filename"));
} catch (JSONException e) {
e.printStackTrace();
}

如果你打算在 JSON 数组中有连续的数字,那么你可以考虑消除它们:

{"filelist": [
{
"filename": "sample.mp3",
"baseurl": "http://etc.com/"
}
]}

需要少一步:

JSONObject jObj;
try {
jObj = new JSONObject(jsonString);
JSONArray jArr = jObj.getJSONArray("filelist");
JSONObject jObj2 = jArr.getJSONObject(0);
textView1.setText(jObj2.getString("filename"));
} catch (JSONException e) {
e.printStackTrace();
}

关于Java JSON 从 JSONArray 的 JSONObject 中的选定名称中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5814142/

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