从 jsonArray java android 获取字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36841971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get string from jsonArray java android
提问by L.B
I am making an android app and have to use json. I am very new to JSON so I have a question. I have got the following json code from a HttpUrlConnection:
我正在制作一个 android 应用程序,必须使用 json。我对 JSON 很陌生,所以我有一个问题。我从 HttpUrlConnection 得到以下 json 代码:
[{"id":"12","name":"John","surname":"Doe","age":"23","username":"123"}]
How can I convert this string to a jsonArray and get the "23" out of this array using java? I already searched a lot on stackoverflow but didn't got the right answer. Hope somebody could help me.
如何将此字符串转换为 jsonArray 并使用 java 从该数组中获取“23”?我已经在 stackoverflow 上搜索了很多,但没有得到正确的答案。希望有人可以帮助我。
I already tried to make it an jsonObject but it didn't work. Result is the string I've got from the HttpUrlConnection:
我已经尝试将其设为 jsonObject,但没有成功。结果是我从 HttpUrlConnection 得到的字符串:
JSONObject jsonObject = new JSONObject(result);
String jsonname = jsonObject.getString("age");
回答by ManoDestra
The JSON string you've supplied is an array (containing a single element). Try using this instead:
您提供的 JSON 字符串是一个数组(包含一个元素)。尝试改用这个:
JSONArray jsonArray = new JSONArray(result);
// This gets you the first (zero indexed) element of the above array.
JSONObject jsonObject = jsonArray.getJSONObject(0);
String age = jsonObject.getString("age");
Similar to thisquestion, but you have the opposite problem.
类似于thisquestion,但你有相反的问题。