2

私はこれに似たJSONを持っています:

{"test":{"red": "on"、 "green": "off"、 "yellow": "on"}、 "test1":{"red": "off"、 "green": "on "、" yellow ":" off "}、" test2 ":{" red ":" on "、" green ":" off "、" yellow ":" off "}}

私はこれを以下のコードで繰り返しました:

    JSONObject t = JSON.parse(params.myObject)

    t.each { id, data ->
        println id
        println data.red
        println data.green
        println data.yellow
    }

ただし、JSONオブジェクトに動的に異なる値を含めることができる場合があります。例(新しい色が追加されました):

{"test":{"red": "on"、 "green": "off"、 "yellow": "on"、 "pink": "on"}、 "test1":{"red": "off "、" green ":" on "、" yellow ":" off "、" pink ":" on "}、" test2 ":{" red ":" on "、" green ":" off "、" yellow ":" off "、" pink ":" on "}}

質問

コードの色をハードコーディングせずにすべてのjsonを反復処理する方法はありますか?

4

2 に答える 2

3
JSONObject t = JSON.parse(params.myObject)
t.each { id, data ->
    println id
    data.each { prop, value ->
       println prop + " = " + value
    }
}
于 2013-02-19T19:24:37.760 に答える
0

私はそれを考え出した。

同様の方法で値を単純に繰り返すことができます。

    t.each { id, data ->
        println id
        data.each {id1, d ->
            println id1
            println  d
        }
    }
于 2013-02-19T19:23:38.437 に答える