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?
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 .
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With