将字符串转换为json对象

时间:2015-08-19 03:50:43

标签: json jsonobject

我想将json字符串转换为json对象。我的json字符串在这里,

{"shop":
{"id":"S56745","name":"adc bakers"},
 "main_items":
    {"cake":
      {"code": ["0001"],"batters":
                        {
                                "item1":{ "id": "1001", "type": "Regular" },
                                "item2":{ "id": "1002", "type": "Chocolate" },
                                "item3":{ "id": "1003", "type": "Blueberry"},
                                "item4":{ "id": "1004", "type": "Devil's Food"}
                    }}}
}

代码是

        if (current_loginStatus == "true") {
            String json_string = EntityUtils.toString(response.getEntity());

}
   JSONObject jObj = null;

    // try parse the string to a JSON object
    try {

    jObj = new JSONObject(json_string);
    Log.i("JSONPARSER::JOBJ Parser", "JSON STRING " + jObj.toString());
    } catch (JSONException e) {
        Log.i("JSON Parser", "Error parsing data " + e.toString());
    }



The output is 

{"shop":
{"id":"S56745","name":"adc bakers"},
 "main_items":
    {"cake":
        {"code": ["0001"],"batters":
                        {
                                "item4":{ "id": "1004", "type": "Devil's Food" },
                                "item2":{ "id": "1002", "type": "Chocolate" },
                                "item3":{ "id": "1003", "type": "Blueberry"},
                                "item1":{ "id": "1001", "type": "Regular"}
                    }}}

 }

问题是,“项目”不是按照json字符串的顺序出现的。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您不应该依赖JSONObject中的键的顺序。

如果您需要明确定义的订单,请改用数组。

在您的情况下,看起来您也可以对键进行排序(它们中包含序列号),但数组看起来是更好的解决方案。