Add JSON utilities
authorDavid ‘Bombe’ Roden <bombe@pterodactylus.net>
Sat, 1 Apr 2017 09:07:39 +0000 (11:07 +0200)
committerDavid ‘Bombe’ Roden <bombe@pterodactylus.net>
Sat, 1 Apr 2017 10:11:54 +0000 (12:11 +0200)
src/main/kotlin/net/pterodactylus/sone/utils/Json.kt [new file with mode: 0644]
src/test/kotlin/net/pterodactylus/sone/utils/JsonTest.kt [new file with mode: 0644]

diff --git a/src/main/kotlin/net/pterodactylus/sone/utils/Json.kt b/src/main/kotlin/net/pterodactylus/sone/utils/Json.kt
new file mode 100644 (file)
index 0000000..7a09a4d
--- /dev/null
@@ -0,0 +1,9 @@
+package net.pterodactylus.sone.utils
+
+import com.fasterxml.jackson.databind.node.ArrayNode
+import com.fasterxml.jackson.databind.node.JsonNodeFactory.instance
+import com.fasterxml.jackson.databind.node.ObjectNode
+
+fun jsonObject(block: ObjectNode.() -> Unit): ObjectNode = ObjectNode(instance).apply(block)
+
+fun Iterable<ObjectNode>.toArray(): ArrayNode = fold(ArrayNode(instance), ArrayNode::add)
diff --git a/src/test/kotlin/net/pterodactylus/sone/utils/JsonTest.kt b/src/test/kotlin/net/pterodactylus/sone/utils/JsonTest.kt
new file mode 100644 (file)
index 0000000..ff741c1
--- /dev/null
@@ -0,0 +1,34 @@
+package net.pterodactylus.sone.utils
+
+import com.fasterxml.jackson.databind.node.ArrayNode
+import com.fasterxml.jackson.databind.node.ObjectNode
+import org.hamcrest.MatcherAssert.assertThat
+import org.hamcrest.Matchers.equalTo
+import org.hamcrest.Matchers.instanceOf
+import org.junit.Test
+
+/**
+ * Unit test for JSON utilities.
+ */
+class JsonTest {
+
+       @Test
+       fun `object node is created correctly`() {
+               val objectNode = jsonObject {
+                       put("foo", "bar")
+               }
+               assertThat(objectNode, instanceOf(ObjectNode::class.java))
+               assertThat(objectNode.toString(), equalTo("{\"foo\":\"bar\"}"))
+       }
+
+       @Test
+       fun `array node is created correctly`() {
+               val arrayNode = listOf(
+                               jsonObject { put("foo", "bar") },
+                               jsonObject { put("baz", "quo") }
+               ).toArray()
+               assertThat(arrayNode, instanceOf(ArrayNode::class.java))
+               assertThat(arrayNode.toString(), equalTo("[{\"foo\":\"bar\"},{\"baz\":\"quo\"}]"))
+       }
+
+}