Richie Richie - 18 days ago 10
Java Question

Convert java.io.BufferedReader to Json object

I have a rest endpoint in a groovy class with a method signature like this....

public PostMyResponse postMyRequest(Reader arg0) throws Exception {


Reader is a java.io.BufferedReader. On my post request I pass in json.

If I do something like this I can see the parameters (Note: I'm aware that this is printing out strings in a java style loop. It's not what I am after)....

int value=0;

// reads to the end of the stream
while((value = arg0.read()) != -1)
{
// converts int to character
char c = (char)value;

// prints character
System.out.println(c);


What I am after is a way to convert the java.io.BufferedReader to a nice Json object using groovy and then to read properties from the json object?

thanks

Answer

Why not just do:

def result = new JsonSlurper().parse(reader)

Then result will be a representation (maps and lists) of whatever JSON was in your reader

Comments