0

I need to build the following json using groovy's JsonBuilder().

[
  {
    "date": "2017-12-08",
    "dog": [
        {
            "name": "Joe",
            "age": "1"
        },
        {
            "name": "Bro",
            "age": "2"
        },
        {
            "name": "Doe",
            "age": "3"
        }       
    ] 
}
]

I cant get the array in the array, because of the date, it wants to always to put date not in the same level as dog array, but put it in { }, like:

[{
    {
    "date": "2017-12-08",
    },
    "dog": [
        {
            "name": "Joe",
            "age": "1"
        },
        {
            "name": "Bro",
            "age": "2"
        },
        {
            "name": "Doe",
            "age": "3"
        }       
    ] 
}
]

1 Answer 1

2

Just stick the date alongside your list in the model:

import groovy.json.JsonBuilder
import groovy.transform.Canonical

@Canonical
class Dog {
    int age
    String name
}

@Canonical
class DogList {
    String date
    List<Dog> dog
}

def ark = [
    new DogList('2017-12-08', [
        new Dog(1, 'Joe'),
        new Dog(2, 'Bro'),
        new Dog(3, 'Doe')
    ])
]

def json = new JsonBuilder(ark).toPrettyString()
println json

prints:

[
    {
        "date": "2017-12-08",
        "dog": [
            {
                "age": 1,
                "name": "Joe"
            },
            {
                "age": 2,
                "name": "Bro"
            },
            {
                "age": 3,
                "name": "Doe"
            }
        ]
    }
]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this works just like I needed. I was getting similar result to yours also, but I was having a unnecessary additional array wrapped around all of it when I used .collect().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.