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?

5
  • In many languages hashes (dictionnaries) are unordered; you should use a method to sort on the key value. Commented Aug 19, 2015 at 3:59
  • why do you care? json is meant to be order independent Commented Aug 19, 2015 at 4:01
  • Maybe this post helps you understand [JSON order mixed up][1] [1]: stackoverflow.com/questions/3948206/json-order-mixed-up Commented Aug 19, 2015 at 4:01
  • What language is this? Please add a tag. Commented Aug 19, 2015 at 4:49
  • How to sort the keys?? Commented Aug 20, 2015 at 4:27

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.