Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
public class JSONObjectExample {
public void java_json_literal() throws Throwable{
JSONObject json = object(
hello -> "world",
bob -> bob,
bill -> object(
was -> was,
here -> here),
john -> array("is", "a", "man"));
assertEquals("world", json.get("hello"));
assertEquals("bob", json.get("bob"));
JSONObject bill = json.getJSONObject("bill");
assertEquals("was", bill.get("was"));
assertEquals("here", bill.get("here"));
JSONArray a = json.getJSONArray("john");
assertEquals("is", a.get(0));
assertEquals("a", a.get(1));
assertEquals("man", a.get(2));
+ "\"john\":[\"is\",\"a\",\"man\"],\"hello\":\"world\"}"
, json.toString());
public static <T> JSONArray array(T... values){
return new JSONArray(values);
public static JSONObject object(NamedValue<?>... keyValuePairs) {
return asList(keyValuePairs)
new JSONObject(),
(jo, kvp) -> jo.put(, kvp.value()),
(jo1, jo2) -> {
jo2.keySet().forEach(n -> jo1.put(n, jo2.get(n)));
return jo1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment