Skip to content
Advertisement

Converter from Json into groovy CODE?

It’s a kind of odd question for an odd situation. I have a large JSON structure which I would like to represent in running groovy code. I need groovy objects that mirror the same structure as the JSON objects.

As to be expected a web search mostly returns results with groovy/json runtime conversion stuff, but nothing about things that output groovy code.

You might think this lazy but really it is a massive JSON structure! A converter would save days!

Advertisement

Answer

You can use Groovy’s own JsonSlurper to parse JSON objects:

import groovy.json.*

def json = '{"name":"john", "surname":"doe", "languages": ["groovy", "python"]}'

def obj = new JsonSlurper().parseText(json)

assert obj.name == "john"
assert obj.surname == "doe"

assert obj.languages.containsAll("python", "groovy")

Of course the class is untyped: it’s only known at runtime. If you want it to be typed, you can write a code which writes the code based on an example (since a json schema may be rare).

EDIT: if you want to generate the model classes code, you can try JSONGen, which “parses JSON to create client side source files to model the JSON data structure”. I’m not aware of a solution for Groovy, but since java-groovy integrations is seamless, it shall work fine.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement