0

I am trying to get an array of all the json keys found in a json file loaded with Google Gson. I have used SomeJsonObject.keySet() in the past, but sets do not preserve the order of their contents.

What I am looking for is something like below:

JsonElement schema_pre = new JsonParser().parse(new FileReader("SchemaFile.json"));
JsonObject schema = gson.fromJson(schema_pre, JsonObject.class);
String[] keys_all = schema.keyArray();
cjmaria
  • 330
  • 4
  • 16
  • 1
    An object is an unordered set of key-value pairs. If you want to make sure order is preserved, use arrays within your JSON file. See the following answer for more details: https://stackoverflow.com/a/4515863/3904086 – Emily Jul 25 '18 at 18:43
  • 1
    *"but sets do not preserve the order"* Which is perfectly fine because JSON object keys are unordered. See http://json.org/: *An object is an **unordered set** of name/value pairs.* – Andreas Jul 25 '18 at 18:51

2 Answers2

2

From JSON RFC7159:

An object is an unordered collection of zero or more name/value pairs [...]

Consequently, the API you are asking for would return more information than actually contained in the JSON object. This behaviour would therefore not comply with the standard.

If you really need an ordering of your JSON objects, you can always express the information in a JSON compliant way by using arrays instead of objects:

{"first":1, "second":2} // Unordered
[{key:"first",value:1}, {key:"second",value:2}] // Ordered

Another motivation for expressing the information as arrays is that keys might change. Most NoSQL databases are capable of creating indexes on object attributes (e.g. MongoDB) and the normalization above is usually the best way to go, even when an ordering is not required

However, if desired, the map you are looking for can still be created as a temporary index for efficient access of JSON objects by looking them up using a specific key.

RedXIII
  • 781
  • 7
  • 6
  • Rather than attempting to get this non-existent information from the JsonObject, is there any other way of getting the keys in order from a .json file? – cjmaria Jul 25 '18 at 18:58
  • 1
    Obviously you can just treat the file as text and try to pull out the relevant pieces that way, but you should really ask if that's something you _should_ do. You'll end up handling two documents that are semantically equivalent (i.e. same keys in different orders) in different ways. – VeeArr Jul 25 '18 at 19:06
1

Consider JsonReader, it reads from beginning to end:

JsonReader reader = new JsonReader(/*Reader*/);

List<Object> objects = new ArrayList<>();

while (reader.hasNext()) {
     String name = reader.nextName();
     /////....
}
voismager
  • 433
  • 4
  • 19