如何解析JsonSluper对象?

时间:2016-04-22 09:43:57

标签: json groovy jsonslurper

我有以下JsonSluper对象:

[ [id:5017,feature:age,value:20],
  [id:2017,feature:city,value:paris],
  [id:3017,feature:country,value:france] ]

我希望得到以下JsonObject

"person":{
    "age":20,
    "city":paris,
    "country":france
}

我想将feature的{​​{1}}值转换为JsonSluper

的字段

1 个答案:

答案 0 :(得分:0)

这是一张地图,而不是" JsonSlurper对象"

假设你有类似的东西:

def object = [[id:5017,feature:'age',value:20],[id:2017,feature:'city',value:'paris'],[id:3017,feature:'country',value:'france']]

然后就这样做:

def json = new JsonBuilder(object).toPrettyString()

然后json将是一个漂亮的json表示,如:

[
    {
        "id": 5017,
        "feature": "age",
        "value": 20
    },
    {
        "id": 2017,
        "feature": "city",
        "value": "paris"
    },
    {
        "id": 3017,
        "feature": "country",
        "value": "france"
    }
]

要进行转换,只需执行以下操作:

def transformed = object.collectEntries { [it.feature, it.value] }
def json = new JsonBuilder(transformed).toPrettyString()