Skip to content

Instantly share code, notes, and snippets.

@takawitter
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takawitter/d3b6f779e71fb4194841 to your computer and use it in GitHub Desktop.
Save takawitter/d3b6f779e71fb4194841 to your computer and use it in GitHub Desktop.
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 {
@Test
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));
assertEquals(
"{\"bob\":\"bob\",\"bill\":{\"here\":\"here\",\"was\":\"was\"},"
+ "\"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)
.stream()
.reduce(
new JSONObject(),
(jo, kvp) -> jo.put(kvp.name(), 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