Search code examples
jsongroovyjsonslurper

How to Parse a JsonSluper object?


I have the following JsonSluper object :

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

and I want to get the following JsonObject:

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

I want to transform the feature value of the JsonSluper to a field of the JsonObject


Solution

  • THat's a Map, not a "JsonSlurper object"

    Assuming you have something like:

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

    Then just do:

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

    Then json will be a pretty json representation like:

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

    To do the transformation, just do:

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