[英]Java JSON pulling value from selected name in JSONObject from JSONArray
我正在尝试从从 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();
}
对于获取单个值,您可以使用 JSONTokener:
JSONObject object = (JSONObject) new JSONTokener("JSON String").nextValue();
String lstatus=object.getString("filename");
这对你有帮助吗?
例如从 json 字符串上方检索文件名
try { String jsonString = new String("{\"filelist\": [{ \"1\": { \"filename\": \"sample.mp3\", \"baseurl\": \"http://www.hostchick.com/deemster/\" }}]}"); JSONObject jObj = new JSONObject(jsonString); JSONArray jArr; jArr = jObj.getJSONArray("filelist"); JSONObject jobj = jArr.getJSONObject(0); String filename = jobj.getJSONObject("1").getString("filename"); Toast.makeText(this, filename, Toast.LENGTH_SHORT).show(); } catch (JSONException e) { e.printStackTrace(); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.