How to write compact JSON objects in Java
Java's syntax is not exactly friendly when trying to create JSON objects. Depending on the JSON library you are using, you end up creating JSON objects either via some kind of mapping from POJOs or you have code like this:
JSONObject object = new JSONObject();
object.put("firstName", "Don");
object.put("lastName", "Draper");
JSONArray array = new JSONArray();
JSONObject kid = new JSONObject();
kid.put("firstName", "Bobby");
kid.put("lastName", "Draper");
array.put(kid);
kid = new JSONObject();
kid.put("firstName", "Sally");
kid.put("lastName", "Draper");
object.put("kids", array);This seems like a lot of code for a simple JSON object.
How can we write this more compact with the limited means of proper Java syntax?
Here is a version that uses (misuses?) static imports and very short method names, along with formatting conventions to get to the same result.
JSONObject object = o( "firstName", "Don",
"lastName", "Draper",
"kids", L( o( "firstName", "Bobby",
"lastName", "Draper"),
o( "firstName", "Sally",
"lastName", "Draper"))
);This is quite a bit more compact. I'm using method o(..) and L(...) to simulate {} and [] respectively. For key/value pairs, a newline has to do.
While one may be tempted to use the syntax for variable initializers directly, it won't work for mixed content, so using method names seems to be the best compromise.
Note that you are gaining readbility, but you are giving up on proper argument checks: The list of arguments for o() needs to be even and you'll only get a runtime exception if it's not. The compiler won't help you here.
Here's the code for this little helper. Use import static com.monoid.json.JSON.*; to compile the example above.
package com.monoid.json;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONCompact {
public static JSONObject o(Object... keyValues) throws JSONException {
JSONObject json = new JSONObject();
for (int i = 0; i < keyValues.length; i+=2) {
json.put(keyValues[i].toString(), keyValues[i+1]);
}
return json;
}
public static JSONArray a(Object...objects) {
JSONArray array = new JSONArray();
for (Object o : objects) {
array.put(o);
}
return array;
}
public static JSONArray L(Object...objects) {
return a(objects);
}
}Do you know a better way to write JSON within Java code?
Let me know in the comments!
