0

I read that JSON.stringify in javascript does not guarantee the result string will contain the fields in the order they appear in the object. Is it safe to assume java's toString on JSONObject will do keep the order that you put keys in the object?

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
Tzvetlin Velev
  • 1,897
  • 2
  • 17
  • 31
  • 1
    Try to google next time... https://stackoverflow.com/questions/24242441/does-json-stringify-preserves-order-of-objects-in-array – Admir Zatega Aug 17 '18 at 19:40
  • @Bucket The duplicate link is useless. OP already knows that `JSON.stringify` doesn't preserve the order. He is asking if java's `toString` has the same issue. – ibrahim mahrir Aug 17 '18 at 19:43
  • 1
    Java’s JSONObject class is [defined as unordered](https://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html) – James Aug 17 '18 at 19:49

1 Answers1

0

You can use gson library for this purpose:

GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder
        .serializeNulls() //comment this if you don't want nulls to show
        .setPrettyPrinting() //comment this if you don't want pretty printing
        .create();
gson.toJson(anyObject);

GsonBuilder class provides a good amount of flexibility when using JSON.

Ali
  • 117
  • 9