0

I have a class called Case which is like:

class Case {
   String caseId;
   Map <String, List<String[]>> listOfCases = new HashMap<String, ArrayList<String[]>>();
}

I created several of these cases and add them to a list. Eventually I want to print the list in JSON format in groovy like:

for (...){
   // creating many of these cases in a loop and adding to caseList
   caseList.add(myCase);
}
// Finally printing them
println new JsonBuilder( caseList ).toPrettyString()

Result looks like this, I chose one only:

{
    "caseId": "Case_1",
    "listOfCases": {
        "server-config.xml": [
            [
                "Core",
                "8"
            ]
        ],
        "server-beans.xml": [
            [
                "plugin",
                "mmap"
            ],
            [
                "maxIdle",
                "16"
            ],
            [
                "minIdle",
                "16"
            ],
            [
                "maxCon",
                "16"
            ]
        ]
    }
}

I want the listOfCases be replaced with Case_1 so each time I create a new Case with the number incremented, the name follows. Is there anyway to customize the jsonBuilder in groovy to do this ?

AlexCon
  • 1,127
  • 1
  • 13
  • 31
  • possible duplicate of [How to modify a JSON in groovy](http://stackoverflow.com/questions/20104819/how-to-modify-a-json-in-groovy) – cfrick Oct 09 '14 at 16:54

1 Answers1

1

As stated in How to modify JSON in groovy changing the content is dangerous, as it attempts to change the original object. The solution presented there is to send the proper map.

You can prepare a map from your data and pass this like this:

class Case {
    String caseId
    Map<String,List<List<String>>> listOfCases
}

def caseList = (1..3).collect{
    new Case(caseId: "Case$it", listOfCases: [ 'abcde': [['1','2'],['4','5']]])
}

println new groovy.json.JsonBuilder(caseList.collect{[caseId: it.caseId, "$it.caseId": it.listOfCases]}).toPrettyString()

results in

[
    {
        "caseId": "Case1",
        "Case1": {
            "abcde": [
    ...
Community
  • 1
  • 1
cfrick
  • 35,203
  • 6
  • 56
  • 68