Skip to content

Instantly share code, notes, and snippets.

@nobusue
Created March 10, 2011 08:34
Show Gist options
  • Save nobusue/863760 to your computer and use it in GitHub Desktop.
Save nobusue/863760 to your computer and use it in GitHub Desktop.
Groovy-1.8で追加されたJsonBulder/JsonSlurperのサンプル(1.8rc2で動作確認)
import groovy.json.*
import static groovy.json.JsonOutput.toJson
def parser = new JsonSlurper()
def s = '''{"a":1, "b":true, "c":"string", "d":"日本語", "e":"\u65E5\u672C\u8A9E"}'''
def o = parser.parseText(s)
assert o.getClass() == HashMap
assert o.a.class == Integer
assert o.b.class == Boolean
assert o.c.class == String
assert o.d == '日本語'
assert o.e == '日本語'
def builder = new JsonBuilder()
builder{
a 1
b true
c 'string'
d '日本語'
e '\u65E5\u672C\u8A9E'
}
assert builder.toString() == '{"a":1,"b":true,"c":"string","d":"日本語","e":"日本語"}'
assert parser.parseText(toJson(o)) == parser.parseText(builder.toString())
assert toJson(o) == builder.toString() //Fail: JSonSluper.parseText()はHashMapを返すので順序は保持されない
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment