java - 如何在 JSON 文件中循环 JSON 数据并解析而不使用数组

标签 java android arrays json loops

我正在尝试解析没有数组的 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/

相关文章:

java - Firebase 数据库高级查询选项

java - 将文件移动到另一个类并且无法使重写的方法正常工作

java - maven war 应用程序设置 contextroot

android GoogleAuthUtil.getTokenWithNotification Intent 回调未触发

java - 如何比较多个字符串数组?

java - .png 文件的 drawImage() 在 Java 小程序中不起作用?

java - Android:第二次调用 onActivityResult 抛出错误

Android 按钮 onclicklistener 动画不起作用

arrays - Perl:自定义排序顺序?

arrays - 在 bash 中使用数组时变量未正确替换