简体   繁体   中英

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!

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.

If you want a Groovy representation of your JSON, you can get that via the built-in JsonSlurper . This will give you Java Maps and Lists of data you can work with.

You can populate more specific, custom objects you've written to represent your JSON entities using the (3rd party) Jackson's data binding functionality (see this question as well).

Try using a JSON parser like this one . According to its documentation you just need to do

JSON.parse

to deserialize the data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM