我正在尝试解析没有数组的 JSON 数据,目前我的代码循环遍历 JSONArray 并且工作正常。
问题/错误
我不知道如何在没有数组的情况下对 JSON 执行相同的操作。当我在没有数组的 JSON 中没有要处理的数组长度时,如何循环。
代码: - 目前适用于带有数组的 JSON 数据
JSONArray inbox = null;
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(INBOX_URL, "GET",
params);
try {
inbox = json.getJSONArray(TAG_ARRAY);
inbox.toString();
// looping through All messages
for (int i = 0; i < inbox.length(); i++) {
JSONObject c = inbox.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String person = c.getString(TAG_PERSON);
…..
…..
…..
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_FROM, person);
…..
…..
…..
没有数组的 JSON
[
{
"id": "1",
"person": "David",
"thur": "",
"grade": "15",
"round": "",
"tour": ""
},
{
"id": "T2",
"person": "Mary",
"thur": "",
"grade": "13",
"round": "",
"tour": ""
},
]
JSON AND ARRAY - 上面的代码对此效果很好
{
"id": [
{
"id": "1",
"person": "Jason",
"thur": "F",
"grade": "17",
"round": "2"
},
{
"id": "2",
"person": "Joe",
"grade": "F",
"score": "16",
"round": "3"
}
]
最佳答案
你试过这个吗?
JSONObject jsonObject = new JSONObject(); try { JSONArray jsonArray = new JSONArray(jsonObject.toString()); } catch (JSONException e) { e.printStackTrace(); }
但我建议您使用 Google Library GSON ( https://github.com/google/gson ) 从其余客户端获取 JSON 值
关于java - 如何在 JSON 文件中循环 JSON 数据并解析而不使用数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31679603/