Alex Brodov
Alex Brodov

Reputation: 3515

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.

Upvotes: 3

Views: 8578

Answers (1)

tim_yates
tim_yates

Reputation: 171054

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"
}

Upvotes: 8

Related Questions