Created
November 5, 2011 07:31
-
-
Save toby55kij/1341239 to your computer and use it in GitHub Desktop.
JsonBuilderを使う際に間違いやすい部分のサンプル(2011/6JGGUG総会のLTで発表した内容を元に解説付き)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//JsonBuilderを使う際に間違いやすい部分のサンプル | |
def json = new groovy.json.JsonBuilder() | |
//サンプル1 | |
json numbers:[1,2,4] | |
def sample1 = json.toString() | |
println sample1 | |
//サンプル2 | |
json { numbers 1,2,4 } | |
def sample2 = json.toString() | |
println sample2 | |
//サンプル3 | |
json { numbers:[1,2,4] } | |
def sample3 = json.toString() | |
println sample3 | |
//サンプル1・2は結果が等しいが、サンプル3は結果が異なる | |
assert sample1 == sample2 | |
assert sample1 != sample3 | |
assert sample2 != sample3 | |
//サンプル1の解説 | |
//callメソッドで引数がMap | |
json.call([numbers:[1,2,4]]) | |
assert sample1 == json.toString() | |
//サンプル2の解説 | |
//callメソッドで引数がクロージャ、内部メソッドのカッコが省略されていた | |
json.call({ numbers(1,2,4) }) | |
assert sample2 == json.toString() | |
//サンプル3の解説 | |
//callメソッドで引数がクロージャ、クロージャ内部はMapなので何もしない | |
json.call({ [numbers:[1,2,4]] }) | |
assert sample3 == json.toString() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment