Modifying org.json to handle duplicate keys

Harshal Parekh
Jun 25 · 3 min read

A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get and opt methods for accessing the values by name, and put methods for adding or replacing values by name.

JSON Object Representation

A sample JSON Object looks something like this:

This article is written with the assumption that you are already familiar with JSON and org.json library in Java.

As per the documentation of JSON: An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique.

But, let’s get past this definition and assume that you have a string with duplicate keys and you have to parse that key into a JSONObject.

Sometimes you have an API response which is flawed and has duplicate keys. Instead of waiting for someone to fix the API, you can write a couple of classes to handle duplicate keys.

Parse the string using wither regex or tokens, add each key-value pair to a hashmap, and in the end recreate your JSON document with the duplicates removed. In this case though I would only remove key-value pairs that are exactly the same. This is not an ideal solution.

Or

Download the source code for org.json.JSONObject, and make a slight modification to the code to automatically leave out duplicates. This is a bit dangerous though. Another option is to create a modified version that simply validates and modifies.

The below code allows you to create a JSONObject with a string containing duplicate keys. Exceptions are thrown only when you have two key-values that have the same key, but different values. This was because I think it would be a problem to choose at random which of the two should be assigned (e.g. the latter value?). Of course this can be changed to work as you wish (e.g. keep last value for multiple keys).

The code above only works for the keys at the first level of JSONObject. To extend the functionality to avoid duplicates in the inner objects as well, the code has to be modified as follows:

The above code can be used as:

This solves your problem of handling duplicate keys.

I hope you enjoyed the article! Find more in my profile. Visit my portfolio here: https://harshal.one.