Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Groovy's JsonSlurper for actual POGO mapping?

Tags:

json

groovy

I've seen countless examples of JsonSlurper used to parse JSON text and create a "JSON object" out of it:

def jsonObject = jsonSlurper.parseText(jsonText)

But what if the JSON text represent one of my FizzBuzz objects? Can I use JsonSlurper to map the JSON object into a FizzBuzz instance? If so, how?

like image 455
smeeb Avatar asked Sep 24 '14 18:09

smeeb


People also ask

What does JsonSlurper do?

JsonSlurper. JsonSlurper is a class that parses JSON text or reader content into Groovy data structures (objects) such as maps, lists and primitive types like Integer , Double , Boolean and String .


1 Answers

After parsing JSON with JsonSlurper You receive a Map. If FizzBuzz has a Map (see here) constructor it should work when parsed Map is passed to constructor.

See the following example:

import groovy.json.JsonSlurper

def json = """{ "name": "John", "age": 127 }"""
def parsed = new JsonSlurper().parseText(json)

def person = parsed as Person

assert person.age == 127
assert person.name == 'John'

class Person {
    String name
    int age    
}
like image 163
Opal Avatar answered Sep 23 '22 12:09

Opal