Last active
August 29, 2015 14:27
-
-
Save takawitter/d3b6f779e71fb4194841 to your computer and use it in GitHub Desktop.
JSONObject version of https://github.com/benjiman/lambda-type-references/blob/master/src/test/java/com/benjiweber/HashLiteralExample.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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