JSON - pford68/groovy-examples GitHub Wiki

Reading JSON

To deserialize JSON strings, use JsonSlurper from the groovy.json package. It takes a String of JSON text and converts it to a Groovy/Java Object.

To read JSON from a file:

  1. As always in Java/Groovy, create a File object, passing the path to the File constructor.
  2. Get the text property of the File. It contains the file content.
  3. Invoke JsonSlurper.parseText() on the content to deserialize it.
import groovy.json.*
import java.net.URI


def ports = [10443, 20443]
def configFile = new File('/users/paford/Downloads/production.json')
def config = configFile.text
def slurper = new JsonSlurper()
def json = slurper.parseText(config)
json.urlMappings.each {
  if (it.path == '/medius-ui/*'){
    def target = new URI(it.target)
    def port = target.port == ports[0] ? ports[1] : ports[0]
    it.target = "https://${target.host}:$port/"
  }
}
configFile.write JsonOutput.prettyPrint(JsonOutput.toJson(json))

Writing JSON

Use JsonOutput.toJson(), in groovy.json, to serialize an Object into a String.

  • It takes any Object as input.
  • It returns the JSON string as output.
  • It is a static method.

Syntax

JsonOutput.toJson(<Object>)  //returns a String

Examples

def json = JsonOutput.toJson([name: 'John Doe', age: 42])
assert json == '{"name":"John Doe","age":42}'  //Trueclass Person { String name }

def json = JsonOutput.toJson([ new Person(name: 'John'), new Person(name: 'Max') ])
assert json == '[{"name":"John"},{"name":"Max"}]'

Writing to a File

To write the JSON to a file, simply send the JSON string from JsonOutput.toJson() to a file the same way you would any text.

Appending to a file

new File('json.txt') << JsonOutput.toJson(json)

Overwriting a file

Use File.write() and use the JSON string as input.

new File('json.txt').write(JsonOutput.prettyPrint(JsonOutput.toJson(json)))

Formatting

The JSON String returned by JsonOutput.toJson() is all on one line, unformatted. To format to be readable, send the output of toJson() to JsonOutput.prettyPrint()

  • It takes a JSON string as input.
  • It returns a well-formatted JSON string output.
  • It is a static method.

Example

def json = slurper.parseText(config)
json.urlMappings.each {
  if (it.path == '/medius-ui/*'){
    def target = new URI(it.target)
    def port = target.port == ports[0] ? ports[1] : ports[0]
    it.target = "https://${target.host}:$port/"
  }
}
configFile.write JsonOutput.prettyPrint(JsonOutput.toJson(json))

Other ways to produce JSON

Another way to create JSON from Groovy is to use JsonBuilder or StreamingJsonBuilder. Both builders provide a DSL which allows to formulate an object graph which is then converted to JSON.

References

⚠️ **GitHub.com Fallback** ⚠️