gpt4 book ai didi

java - 如何在 Groovy 中处理动态 JSON 元素

转载 作者:行者123 更新时间:2023-12-02 13:57:24 26 4
gpt4 key购买 nike

我有类似于此的 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 而无需在我的代码中对颜色进行硬编码?

最佳答案

JSONObject t = JSON.parse(params.myObject)
t.each { id, data ->
println id
data.each { prop, value ->
println prop + " = " + value
}
}

关于java - 如何在 Groovy 中处理动态 JSON 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14965466/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com