-1

I am using a Java JSON object to store some data. But when I printed it, I found that it stores the data randomly. For example, I stored data like this:

obj.put("key1","val1");
obj.put("key2","val2");

And when I printed it:

{"key2":"val2","key1":"val1"}'

I googled it and found that JSON objects are unordered sets of key value pair. So it doesn't store the order of data.

I need some help in storing data in a JSON object with their order.

Necreaux
  • 9,451
  • 7
  • 26
  • 43
Anita
  • 2,352
  • 2
  • 19
  • 30
  • 3
    Well, if you want that, don't use JSON because the RFC itself (RFC 7159) explicitly mentions that the order of object members does not matter – fge Feb 24 '15 at 13:33
  • 1
    http://stackoverflow.com/questions/7214293/is-the-order-of-elements-in-a-json-list-maintained – Adam Siemion Feb 24 '15 at 13:35
  • Use JSONArray instead. – Sachin Gadagi Feb 24 '15 at 14:14
  • Using JSON, it's most likely that you are using it for interfaces. If the other endpoint on the interface is doing it right, you could break their (de)serialization. Don't be that person. – stuXnet Feb 24 '15 at 14:32

1 Answers1

0

Arrays are ordered so use an array of key-value objects [ {key1: val1}, {key2: val2} ]

simbo1905
  • 6,321
  • 5
  • 58
  • 86