jsongroovyjsonbuilder

Groovy - Constructing json from String


I'm using Groovy, i've tried to create a simple function which will construct a Json object from a provided Json string, then i'm trying to print this string but unfortunate it's adding Square brackets to the output.

Here's a snippet from my code:

def JsonBuilder ConstructJsonObject (jsonStr) {
    def jsonToReturn = new JsonBuilder();
    def root = jsonToReturn(jsonStr);
    return jsonToReturn;
}

String jsonStr = "{id: '111'}";
println(jsonStr);
def jsonObject = ConstructJsonObject(jsonStr);
println(jsonObject.toPrettyString());

And here's the output:

{id: '111'}

[ "{id: '111'}" ]

It's returning an Array and not a pure Json.


Solution

  • If you change your input to be valid json (with double quotes round the keys and values), you can do:

    import groovy.json.*
    
    String jsonStr = '{"id": "111"}'
    println new JsonBuilder(new JsonSlurper().parseText(jsonStr)).toPrettyString()
    

    To print

    {
        "id": "111"
    }