From ccc17ddce331a6c70e3e6a14df34ca73c05ed012 Mon Sep 17 00:00:00 2001 From: =?utf8?q?David=20=E2=80=98Bombe=E2=80=99=20Roden?= Date: Sat, 1 Apr 2017 11:07:39 +0200 Subject: [PATCH] Add JSON utilities --- .../kotlin/net/pterodactylus/sone/utils/Json.kt | 9 ++++++ .../net/pterodactylus/sone/utils/JsonTest.kt | 34 ++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 src/main/kotlin/net/pterodactylus/sone/utils/Json.kt create mode 100644 src/test/kotlin/net/pterodactylus/sone/utils/JsonTest.kt 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\"}]")) + } + +} -- 2.7.4