Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON to Groovy parser

Tags:

I found many things about converting Groovy to JSON, but oddly enough, not the other way.

What is the (best) JSON to Groovy parser around there ?

like image 982
Gzorg Avatar asked Dec 10 '09 23:12

Gzorg


People also ask

How do I iterate through a JSON array in groovy?

Use that to create a JSON array. You then loop through the array for (int i = 0; i < array. length(); i++) and retrieve each JSON object by calling array. getJSONObject(i); which returns JSONObject .

How do I create a JSON object in Groovy?

Groovy 1.8 introduced json package for parsing and building JSON data. JsonSlurper is used for parsing JSON and JsonBuilder is used for creating JSON in Groovy. For more details visit the API here and a good article here.


1 Answers

If you are on Groovy 1.8 or later, there is a build in JsonSlurper you can use this way:

import groovy.json.JsonSlurper  //Attention: you have to use double quotes inside the json string def jsonObj = new JsonSlurper().parseText( '{ "name":"Peter", "age": 23}' )  assert jsonObj.name == "Peter" assert jsonObj.age == 23 //this won't work, because it's not defined assert jsonObj.gender == null 
like image 115
Fa11enAngel Avatar answered Jan 05 '23 05:01

Fa11enAngel