将json字符串转换为json对象而不更改键顺序

时间:2015-10-07 10:09:08

标签: android json

我有一个json字符串,如下所示

{
"college": {
    "id": "RPD4007",
    "address": "#302, 1 st cross"
},
"deparment": {
    "department1": {
        "name": {
            "maths": {
                "chapter": 1,
                "name": "algebra",
                "module_id": "01"
            },
            "electronics": {
                "chapter": 1,
                "name": "ec",
                "module_id": "01"
            }
        }
    },
    "department2": {
        "name": {
            "english": {
                "chapter": 2,
                "name": "algebra",
                "module_id": "02"
            },
            "electrical": {
                "chapter": 2,
                "name": "algebra",
                "module_id": "02"
            }
        }
    }
}
}

我试图将这个json sring转换为json对象,

string json_string = EntityUtils.toString(response.getEntity());
jObj = new JSONObject(json_string);//json object
JSONObject object = jobj.getJSONObject("college");

但是我得到的jobj输出与json字符串的顺序相反。如下所示,

{
"college": {
    "id": "RPD4007",
    "address": "#302, 1 st cross"
},
"deparment": {
    "department2": {
        "name": {
            "electrical": {
                "chapter": 2,
                "name": "algebra",
                "module_id": "02"
            },
            "english": {
                "chapter": 2,
                "name": "algebra",
                "module_id": "02"
            }
        }
    },
    "department1": {
        "name": {
            "electronics": {
                "chapter": 1,
                "name": "ec",
                "module_id": "01"
            },
            "maths": {
                "chapter": 1,
                "name": "algebra",
                "module_id": "01"
            }
        }
    }
}
}

如何以相同的顺序获得它?

2 个答案:

答案 0 :(得分:0)

我认为你正在制作jsonObject两次。 做这样的事情 你有包含JSON数据的String 为你所做的事做一个对象

string json_string = EntityUtils.toString(response.getEntity());
jObj = new JSONObject(json_string);//json object

然后使用

创建一个循环以获取该对象内的对象
 String college = jobj.getString("college");

答案 1 :(得分:-1)

答案在这里:JSON order mixed up

因此,JSON库可以根据需要自由重新排列元素的顺序。这不是一个错误。