2015-10-07 147 views
2

我有一个JSON字符串如下图所示转换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

可能[获取该对象内的对象重复](http://stackoverflow.com/a/4920304) –

+0

可能重复的[JSON顺序混合](http://stackoverflow.com/questions/3948206/json-order-mixed-up) – FWeigl

+1

http:///stackoverflow.com/a/4515863/3514144 –

回答

0

这里的答案:JSON order mixed up

因此,JSON库可以自由地重新排列元素的顺序,因为他们认为合适的。这不是一个错误。

0

我认为你做了两次jsonObject。 就做这样的事情 你有字符串,其中包含JSON数据 使对象为你做

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

然后进行循环使用

String college = jobj.getString("college");