Using Groovy JsonSlurper to actually display POGO?

I have seen countless JsonSlurper examples used to parse JSON text and create a "JSON object" from it:

def jsonObject = jsonSlurper.parseText(jsonText) 

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

+6
source share
1 answer

After parsing JSON with JsonSlurper you get a Map . If FizzBuzz has a Map constructor (see here ), it should work when Map parsing is passed to the 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 } 
+8
source

Source: https://habr.com/ru/post/975797/


All Articles