3

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.

1
  • Have you tried the JsonSlurper? If you want to parse JSON from a string: groovy-lang.org/json.html Commented Oct 20, 2015 at 16:07

1 Answer 1

8

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"
}
Sign up to request clarification or add additional context in comments.

Comments

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.