3

I am using the JSONArray object and I am passing to the constructor of that object a string. The string that I'm passing is

[{\"x\":18.4300,\"y\":30.4700,\"w\":53.0900,\"fontSize\": 11,\"bold\": 0,\"charcount\": 22,\"id\": 349133}].

After out-printing the json object, I get the following:

[{"charcount":22,"w":53.09,"x":18.43,"y":30.47,"fontSize":11,"bold":0,"id":349133}].

Can I get an example in code of how I can preserve the order of the original json string?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Patrick
  • 51
  • 7
  • 4
    JSON (like a HashMap), has no natural ordering. This is an XY Problem unless you explain why order matters – OneCricketeer May 27 '17 at 19:40
  • you could replace JSONArray with Jackson see https://stackoverflow.com/questions/19272830/order-of-json-objects-using-jacksons-objectmapper – Hector May 27 '17 at 20:00

1 Answers1

0

You can use a an ordered collection to parse your json to keep it's order. A sample for your json:

    String json = "[{\"x\":18.4300,\"y\":30.4700,\"w\":53.0900,\"fontSize\": 11,\"bold\": 0,\"charcount\": 22,\"id\": 349133}]";
    Gson gson = new Gson();
    Type type = new TypeToken<Set<LinkedTreeMap<String, Object>>>() {}.getType();
    Set<LinkedTreeMap<String, Object>> myMap = gson.fromJson(json, type);
    System.out.println(json);
    System.out.println(myMap);
TuyenNTA
  • 1,194
  • 1
  • 11
  • 19