2

我有类似于此的 JSON:

{"test":{"red":"on","green":"off","yellow":"on"},"test1":{"red":"off","green":"on ","黄色":"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 ":"关","粉色":"开"}}

问题

有没有一种方法可以遍历所有 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 回答