cicit
cicit

Reputation: 591

Groovy returning JSON

I have the following Groovy script (not a Grails app) that is returning a JSON-like, but it is not strictly valid JSON.

 String baseURL = 'https://test.com'
 File userFile = new File("./user.json")
 def client = new HTTPBuilder(baseUrl)
 client.headers['Content-Type'] = 'application/json'
 client.request(GET, JSON) { req ->
     requestContentType = JSON
     headers.Accept = 'application/json'
     response.success = { resp, json ->
        userFile.append json.toString()
        println JsonOutput.toJson(json.toString())
     }
 }

I am trying to create a JSON output file. I have tried using JsonOutput.prettyPrint and I looked at JsonBuilder, but that looks like I would have to build the JSON structure manually when Groovy should support the output. This is what I am getting back.

{AssetNumber=AssetNumber1, DeviceFriendlyName=FriendlyName1, PhoneNumber=17035551231, SerialNumber=SerialNumber1, Udid=Udid1, [email protected], UserId=userId1, UserName=userName1}

As I said, this is JSON-like, but not strictly valid. I was expecting something like:

{"AssetNumber": "AssetNumber1", "DeviceFriendlyName": "FriendlyName1"....}

Any ideas?

Upvotes: 1

Views: 4496

Answers (1)

Opal
Opal

Reputation: 84884

It works perfectly fine (groovy v 2.3.6):

import groovy.json.*

def pretty = JsonOutput.prettyPrint(JsonOutput.toJson([1:2]))

assert pretty == """{
    "1": 2
}"""

In this closure:

response.success = { resp, json ->
   userFile.append json.toString()
   println JsonOutput.toJson(json.toString())
}

You're getting an instance of Map under json variable. You do not need to turn it into a string. Instead use:

   userFile.append JsonOutput.toJson(json)
   println JsonOutput.toJson(json)

Upvotes: 1

Related Questions