我正在尝试从JSONArray创建的JSONbject中的名称中提取值,而JSONAarray是从main(root)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 - Java JSON从JSONArray中从JSONObject中的选定名称中提取值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5814142/