Skip to content

Instantly share code, notes, and snippets.

@nobeans
Created November 17, 2016 06:39
Show Gist options
  • Save nobeans/f2d5432776c6d3b76894c92539d4173b to your computer and use it in GitHub Desktop.
Save nobeans/f2d5432776c6d3b76894c92539d4173b to your computer and use it in GitHub Desktop.
import groovy.json.*
def test(jsonText) {
new JsonSlurper().parseText(jsonText)
}
def jsonText = '{"a": 1, "b": [2,3,{"c": 999}]}'
assert test(jsonText) == [a:1, b:[2, 3, [c:999]]]
assert test('[]') == []
assert test('{}') == [:]
assert test('1') == 1
def e = groovy.test.GroovyAssert.shouldFail {
test('')
}
assert e instanceof java.lang.IllegalArgumentException
assert e.message == "Text must not be null or empty"
assert test(jsonText).getClass() == groovy.json.internal.LazyMap
assert test(jsonText).b.getClass() == java.util.ArrayList
assert test(jsonText).b[2] == [c:999]
assert test(jsonText).b[2].getClass() == groovy.json.internal.LazyMap
assert test(jsonText).hoge == null
assert test(jsonText).collectEntries { it } == [a:1, b:[2, 3, [c:999]]]
assert test(jsonText).collectEntries { it }.getClass() == java.util.LinkedHashMap
assert test(jsonText).collectEntries { it }.b.getClass() == java.util.ArrayList
assert test(jsonText).collectEntries { it }.b[2].getClass() == groovy.json.internal.LazyMap // !!!!
def convertRecursively(obj) {
if (obj instanceof Map) return obj.collectEntries { key, value -> [key, convertRecursively(value)] }
if (obj instanceof List) return obj.collect { convertRecursively(it) }
return obj
}
assert convertRecursively(test(jsonText)) == [a:1, b:[2, 3, [c:999]]]
assert convertRecursively(test(jsonText)).getClass() == java.util.LinkedHashMap
assert convertRecursively(test(jsonText)).b.getClass() == java.util.ArrayList
assert convertRecursively(test(jsonText)).b[2].getClass() == java.util.LinkedHashMap // !!!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment