0

From a separate system I get a String parameter "messageJson" whose content is in the form:

{"agent1":"smith","agent2":"brown","agent3":{"agent3_1":"jones","agent3_2":"johnson"}}

To use it in my program I parse it with JsonSlurper.

def myJson = new JsonSlurper().parseText(messageJson)

But the resulting Json has the form:

[agent1:smith, agent2:brown, agent3:[agent3_1:jones, agent3_2:johnson]]

Note the square brackets and the lack of double quotes. How can I parse messageJson so that the original structure is kept?

2
  • This is no JSON - its the .toString() from Groovy; JsonSlurper reads the JSON and turns it into Map:s. Commented Aug 2, 2019 at 10:43
  • @cfrick Thanks, I misunderstood JsonSlurper. I've tried it now with JsonOutput.toJson, but the result is {\"agent1\":\"smith\",\"agent2":\"brown\", ... and so on. How can I get the original format in a format that I can work with? I need to be able to add and remove keys and afterwards send the Json along to another system in the correct format. Commented Aug 2, 2019 at 10:56

1 Answer 1

2

Ok, thanks to the hint by cfrick, I was able to find a solution. In case anyone else has a similar problem, all I needed to do was using JsonOutput in the end to convert the map back to a Json

I.E. :

def myJson = new JsonSlurper().parseText(messageJson)
myJson << [agent4:"jane"]
def backToJson = JsonOutput.toJson(myJson)
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.