0

I want to convert a json string to json object.My json string is here ,

{"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"}
                    }}}
}

The code is

        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"}
                    }}}

 }

the problem is , the 'items' are not coming as in the order of json string. How can i solve this issue?

1 Answers1

1

You should not depend on the order of keys in a JSONObject.

If you need a well-defined order, use an array instead.

In your case, it looks like you can also sort the keys (they have sequence numbers in them), but array looks like a better solution.

Thilo
  • 257,207
  • 101
  • 511
  • 656