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}
source share