From: David ‘Bombe’ Roden Date: Sat, 1 Apr 2017 09:07:39 +0000 (+0200) Subject: Add JSON utilities X-Git-Tag: 0.9.7^2~271 X-Git-Url: https://git.pterodactylus.net/?a=commitdiff_plain;h=ccc17ddce331a6c70e3e6a14df34ca73c05ed012;p=Sone.git Add JSON utilities --- 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 index 0000000..7a09a4d --- /dev/null +++ b/src/main/kotlin/net/pterodactylus/sone/utils/Json.kt @@ -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.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 index 0000000..ff741c1 --- /dev/null +++ b/src/test/kotlin/net/pterodactylus/sone/utils/JsonTest.kt @@ -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\"}]")) + } + +}