Make Gson an exception when parsing JSON with a duplicate key

I am parsing a simple JSON object with Gson. I want it to throw some error when the key name is duplicated. For instance.

{ a: 2, a: 3 } 

In my case, Gson parses such JSON and sets the value to 3. I want it to make some kind of exception.

I know that I can parse JSON as a map, and then Gson throws an exception in this case, but only if the duplicated key is not embedded in the map. If I have, for example, JSON like this:

 { a: 2, b: { dup: 1, dup: 2 } } 

However, it is parsed without any exception, and I only have one "dup" with a value of 2.

Can I somehow configure Gson to error in this case? Or have duplicate entries in an instance of JsonObject so that I can detect it myself (but I doubt that, since that would be incorrect JsonObject )

Reproducible example

 String json = "{\"a\":2, \"a\":3}"; Gson gson = new Gson(); JsonObject jsonObject = gson.fromJson(json, JsonObject.class); System.out.println(jsonObject); 

displays

 {"a":3} 
+6
source share
1 answer

1) You can change the gson source a bit. This is just a suggestion to understand how everything works. I do not advise you to use this in a real / production environment.

Gson uses com.google.gson.internal.LinkedTreeMap when parsing a json string on a JsonObject . For testing problems, you can copy this class to your project with the same name and package name. And edit its put method to prevent duplicate keys.

  @Override public V put(K key, V value) { if (key == null) { throw new NullPointerException("key == null"); } // my edit here if(find(key, false) != null) { throw new IllegalArgumentException("'" + key.toString() + "' is duplicate key for json!"); } Node<K, V> created = find(key, true); V result = created.value; created.value = value; return result; } 

2) Another clean solution is to define custom classes that will map to your json strings. Then write your own TypeAdapters

3) Do it using the Deserializer ? I do not think that's possible. If you try to use it, you will see that you already have jsonObject in which your duplicate keys are treated like.

+3
source

All Articles