{"id":34827,"date":"2016-03-18T15:00:42","date_gmt":"2016-03-18T13:00:42","guid":{"rendered":"http:\/\/examples.javacodegeeks.com\/?p=34827"},"modified":"2019-03-29T14:25:34","modified_gmt":"2019-03-29T12:25:34","slug":"groovy-json-example","status":"publish","type":"post","link":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/","title":{"rendered":"Groovy Json Example"},"content":{"rendered":"<p>In this article we will see how to manipulate <code>JSON<\/code> data in <code>Groovy<\/code>. JSON (JavaScript Object Notation) is the much preferred data format these days for the exchange of data between the interested parties (client and server), due to its light weight nature and ease of use.<\/p>\n<p>Groovy has a built in support to work with JSON data &#8211; be it with the literal data or the the Java objects in memory. It offers a simple way to parse and build the data into JSON format.<\/p>\n<p>This article will show the various situations in which you need to have a JSON format.<br \/>\n&nbsp;<br \/>\n&nbsp;<br \/>\n&nbsp;\n<\/p>\n<h2>1. Environment<\/h2>\n<p>The examples shown below are executed in the <i>Command Prompt \/ Shell<\/i>. But they are guaranteed to work with any of the IDEs (like <i>Eclipse, IntelliJ IDEA, Netbeans<\/i>) through the respective plugins. The examples are executed with the Groovy Version <strong>Groovy Version: 2.4.3<\/strong>.<\/p>\n<h2>2. Important Classes<\/h2>\n<p>Since version 1.8, Groovy offers two classes viz <code><strong>JsonSlurper<\/strong><\/code> and <code><strong>JsonBuilder<\/strong><\/code>. These classes offer various methods to help us deal with the JSON data.<\/p>\n<p><strong>JsonSlurper<\/strong> is a parser which reads the input data and gets the JSON content backed up by a Java Collection (Map or List). By iterating the Collection we can get the required JSON data in the form of Domain Model class (POJO\/POGO) to be used in further layers of the application. The term POJO stands for Plain Old Java Object and POGO stands for Plain Old Groovy Object. The JsonSlurper can read from various different inputs ranging from literal String, File, URL, Map etc.,<\/p>\n<p><strong>JsonBuilder<\/strong> class helps you to build the JSON data from your existing Domain Class (or POGO). Using the JSONBuilder object you can either get the JSON data in a ordinary String (which will be compressed and not so good for human reading), <em>prettyPrint<\/em> format (neatly formatted content for display which will be human readable), write the data into a file etc.,<\/p>\n<p>In addition to these classes, we have an another useful Utiltity class called <code>JsonOutput<\/code>.<\/p>\n<p><strong>JSONOutput<\/strong> is a helper class facilitating the transformation of the JSON content from various source formats through its overloaded method toJson(). You can use the relevant method to get the JSON output from the underlying source which is passed as argument. It also offers a <code><em>prettyPrint<\/em><\/code> method for a human readable output.<\/p>\n<p>For example, <code>toJson(String string)<\/code> produces the JSON representation for the String data passed, whereas <code>toJson(Map map)<\/code> returns the JSON representation for a Map that is passed as an argument.<\/p>\n<p>We will use a mixture of all these in the below set of examples.<\/p>\n<blockquote>\n<p>Please note that these classes belong to the package <code><strong>groovy.json<\/strong><\/code> and this package is <em><strong>NOT<\/strong> imported<\/em> by default. We need to <em>explicitly import<\/em> the classes to be available in our groovy scripts.<\/p>\n<\/blockquote>\n<h2>3. JSON Examples<\/h2>\n<p>We will see a set of examples for different scenarios to work with JSON output. The source code and output are mostly self explanatory and hence will have a minimal explanation wherever required.<\/p>\n<h3>3.1. Producing JSON data from a literal String<\/h3>\n<p>Let us see a very simple example where we can produce the JSON data from a plain text (literal String) without actually generating an object. We will use <code>JsonOutput<\/code> class for this purpose.<\/p>\n<p><span style=\"text-decoration: underline\"><em>JsonLiteral.groovy<\/em><\/span><\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.example.groovy.json;\n\nimport groovy.json.JsonOutput;\n\ndef jsonLiteral = [\"name\": \"Raghavan\", \"id\" : 1]\n\nprintln \"JSON Literal as String : \" + jsonLiteral\nprintln \"JSON Literal as JSON : \" + JsonOutput.toJson(jsonLiteral)\nprintln \"JSON Literal as JSON formatted : \"\nprintln JsonOutput.prettyPrint(JsonOutput.toJson(jsonLiteral))\n\n<\/pre>\n<p>The above script produces the following output.<\/p>\n<pre class=\"brush:java\">JSON Literal as String : [name:Raghavan, id:1]\nJSON Literal as JSON   : {\"name\":\"Raghavan\",\"id\":1}\nJSON Literal as JSON formatted : \n{\n    \"name\": \"Raghavan\",\n    \"id\": 1\n}\n<\/pre>\n<h3>3.2. Producing JSON data from a POGO<\/h3>\n<p>Let us see an example where we can generate the JSON output from a <code>POGO (Plain Old Groovy Object)<\/code>.<\/p>\n<p><span style=\"text-decoration: underline\"><em>JsonFromPOGO.groovy<\/em><\/span><\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.example.groovy.json;\n\nimport groovy.json.JsonOutput\n\nclass Person\n{\n    String name\n    int age\n    \n    String toString()\n    {\n        \"[Person] name : ${name}, age : ${age}\"\n    }\n}\ndef person = new Person(name:'Raghavan',age:34)\nprintln \"Person Object : \" + person\nprintln \"Person Object in JSON : \" + JsonOutput.toJson(person)\nprintln \"JSON Pretty Print\"\nprintln \"-----------------\"\n\/\/ prettyPrint requires a String and NOT an Object\nprintln JsonOutput.prettyPrint(JsonOutput.toJson(person))\nprintln \"\"\n\n\/* Let us work with a list of Person instances *\/\ndef json = JsonOutput.toJson([new Person(name : \"Vignesh\", age : 50),\n            new Person(name : \"Murugan\", age: 45)])\nprintln \"JSON Object List : \" + json\nprintln \"JSON Pretty Print \"\nprintln \"------------------\"\nprintln JsonOutput.prettyPrint(json)\n\n<\/pre>\n<p>Please note that we have used two different <code>toJson(..)<\/code> methods above. Depending on the input argument passed (<code>Object<\/code>, <code>List<\/code>) the corresponding overloaded <code>toJson()<\/code> method will be invoked.<\/p>\n<p>The above script produces the following output.<\/p>\n<pre class=\"brush:java\">Person Object : [Person] name : Raghavan, age : 34\nPerson Object in JSON : {\"age\":34,\"name\":\"Raghavan\"}\nJSON Pretty Print\n-----------------\n{\n    \"age\": 34,\n    \"name\": \"Raghavan\"\n}\n\nJSON Object List : [{\"age\":50,\"name\":\"Vignesh\"},{\"age\":45,\"name\":\"Murugan\"}]\nJSON Pretty Print \n------------------\n[\n    {\n        \"age\": 50,\n        \"name\": \"Vignesh\"\n    },\n    {\n        \"age\": 45,\n        \"name\": \"Murugan\"\n    }\n]\n<\/pre>\n<h3>3.3. Producing JSON data via JSONSlurper using literal String<\/h3>\n<p><code>JsonSlurper<\/code> object gives us a <em>JSON Object<\/em> as a result of successful parsing of the input content passed to it. It has several overloaded methods parse() which accepts various different input sources right from literal String, File, URL, Map etc.,<\/p>\n<p>We can use this JSON Object to fetch any properties of our interest by using the relevant hierarchy \/ relation.<\/p>\n<p>We will see how we can generate the JSON output with the JsonSlurper instance below.<div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<p><span style=\"text-decoration: underline\"><em>JsonSlurper1Basic.groovy<\/em><\/span><\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.example.groovy.json;\n\nimport groovy.json.JsonSlurper\n\ndef jsonSlurper = new JsonSlurper()\ndef inputText = '{\"name\" : \"Groovy\", \"year\": 2005}'\n\ndef jsonObject = jsonSlurper.parseText(inputText)\nprintln \"JSONObject generated out of JsonSlurper : \" + jsonObject\n\nprintln \"jsonObject is of type : \" +  jsonObject.getClass()\nprintln \"jsonObject is a Map ? \" + (jsonObject instanceof Map)\nassert jsonObject instanceof Map\n\nprintln \"\"\nprintln \"Individual Attributes\"\nprintln \"=====================\"\nprintln \"Object.name -&gt; [\" + jsonObject.name + \"]\"\nprintln \"Object.year -&gt; [\" + jsonObject.year + \"]\"\n\n<\/pre>\n<p>The above script produces the following output.<\/p>\n<pre class=\"brush:java\">JSONObject generated out of JsonSlurper : [name:Groovy, year:2005]\njsonObject is of type : class groovy.json.internal.LazyMap\njsonObject is a Map ? true\n\nIndividual Attributes\n=====================\nObject.name -&gt; [Groovy]\nObject.year -&gt; [2005]\n\n<\/pre>\n<p>In this example, we have used a literal text to be parsed by <code>JsonSlurper<\/code> instance and as a result we get a JSON Object. You can see that &#8216;jsonObject&#8217; is of type &#8216;<code><strong>Map<\/strong><\/code>&#8216; (<code><em>groovy.json.internal.LazyMap<\/em><\/code>).<\/p>\n<p>Later, we can retrieve the properties from a map using the usual dot notation (&#8220;.&#8221;) as in <em>jsonObject.name<\/em> and <em>jsonObject.year<\/em> respectively.<\/p>\n<h3>3.4. Producing JSON data via JSONSlurper using POGO Instance(s)<\/h3>\n<p>We can see how we can pass a literal String with a List object to be parsed by <code>JsonSlurper<\/code> and how we can manipulate the contents of a list.<\/p>\n<p><span style=\"text-decoration: underline\"><em>JsonSlurper2List.groovy<\/em><\/span><\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.example.groovy.json;\n\nimport groovy.json.JsonSlurper\n\ndef jsonSlurper = new JsonSlurper()\ndef jsonObject = jsonSlurper.parseText('{ \"vowels\" : [\"a\", \"e\", \"i\", \"o\", \"u\"] }')\n\nprintln \"Json Object : \" + jsonObject\nprintln \"Json Object Type : \" + jsonObject.getClass()\nprintln \"\"\n\nprintln \"Json Object - vowels : \" + jsonObject.vowels\nprintln \"Json Object - vowels Type : \" + jsonObject.vowels.getClass()\nprintln \"Json Object - vowels is a List ? \" + (jsonObject.vowels instanceof List)\ndef listSize = jsonObject.vowels.size\nprintln \"Json Object - vowels Size : \" + listSize\nprintln \"Json Object - vowels = first element : \" + jsonObject.vowels.get(0)\nprintln \"Json Object - vowels = last  element : \" + jsonObject.vowels.get(listSize-1)\n\n<\/pre>\n<p>The above script produces the following output.<\/p>\n<pre class=\"brush:java\">Json Object : [vowels:[a, e, i, o, u]]\nJson Object Type : class groovy.json.internal.LazyMap\n\nJson Object - vowels : [a, e, i, o, u]\nJson Object - vowels Type : class java.util.ArrayList\nJson Object - vowels is a List ? true\nJson Object - vowels Size : 5\nJson Object - vowels = first element : a\nJson Object - vowels = last  element : u\n\n<\/pre>\n<h3>3.5. Producing JSON data via JSONSlurper and verify the data type of attributes<\/h3>\n<p>Below example code snippet shows that we can retrieve the data type of each of the members parsed out of JsonSlurper, which will be helpful for us to take a cautious decision while passing it further into the application.<\/p>\n<p><span style=\"text-decoration: underline\"><em>JsonSlurper3DataTypes.groovy<\/em><\/span><\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.example.groovy.json;\n\nimport groovy.json.JsonSlurper\n\ndef jsonSlurper = new JsonSlurper()\ndef jsonObject = jsonSlurper.parseText '''\n    {\n        \"name\"        : \"Raghavan\",\n        \"age\"         : 23,\n        \"temp\"        : 98.4,\n        \"salary\"      : 40000.25\n    }\n'''\n\nprintln \"JSON Object :  \" + jsonObject\nprintln \"JSON Object class : \" + jsonObject.getClass()\nprintln \"\"\nprintln \"Individual Attributes and Data types \"\nprintln \"======================================\"\nprintln \"Datatype of name :  \" + jsonObject.name.class\nprintln \"Datatype of age : \" + jsonObject.age.class\nprintln \"Datatype of temp : \" + jsonObject.temp.class\nprintln \"Datatype of salary : \" + jsonObject.salary.class\n\n\n<\/pre>\n<p>In this example, we have used a different way of passing a literal text to JsonSlurper through a set of triple quotes (&#8221;&#8217;) for a multi-line string literal input.<\/p>\n<p>The above script produces the following output, where you can see the data type of each of the members printed out in order. Please note that Groovy prefers <code><em>BigDecimal<\/em><\/code>, unlike Java which prefers a <code>float<\/code> or <code>double<\/code> for the floating point values.<\/p>\n<pre class=\"brush:java\">JSON Object :  [age:23, name:Raghavan, salary:40000.25, temp:98.4]\nJSON Object class : class groovy.json.internal.LazyMap\n\nIndividual Attributes and Data types \n======================================\nDatatype of name :  class java.lang.String\nDatatype of age : class java.lang.Integer\nDatatype of temp : class java.math.BigDecimal\nDatatype of salary : class java.math.BigDecimal\n\n<\/pre>\n<h3>3.6. Parsing JSON data via JsonSlurper by reading an input file<\/h3>\n<p>We will see an example of how to read the json file from disk and work with the contents retrieved inside our groovy script.<\/p>\n<p>We will read the contents of the file &#8217;employee.json&#8217; and also display the same with and without pretty print for your ease of use and verification.<\/p>\n<p><span style=\"text-decoration: underline\"><em>JsonSlurper4File.groovy<\/em><\/span><\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.example.groovy.json;\n\nimport groovy.json.JsonSlurper\nimport groovy.json.JsonOutput\n\nString inputFile = 'employee.json'\nString fileContents = new File(inputFile).getText('UTF-8')\n\ndef jsonSlurper = new JsonSlurper()\ndef jsonObject = jsonSlurper.parseText(fileContents)\n\nprintln \"JSONObject : \" + jsonObject\nprintln \"\"\nprintln \"JSONObject type : \" + jsonObject.getClass()\nprintln \" \"\nprintln \"JSONObject pretty printed\"\nprintln \"=========================\"\nprintln JsonOutput.prettyPrint(fileContents)\nprintln \"\"\nprintln \"Individual Attributes\"\nprintln \"---------------------\"\nprintln \"JSONObject employee firstName : \" + jsonObject.employee.firstName\nprintln \"JSONObject employee age : \" + jsonObject.employee.age\nprintln \"JSONObject employee project name : \" + jsonObject.employee.project.name\n\n<\/pre>\n<p>The above script produces the following output. You can see the attributes of the object being retrieved from the JSON Object.<\/p>\n<pre class=\"brush:java\">JSONObject : [employee:[age:35, country:India, department:Technology, firstName:Raghavan, lastName:Muthu, project:[manager:Mark, name:Payroll Automation]]]\n\nJSONObject type : class groovy.json.internal.LazyMap\n\nJSONObject pretty printed\n=========================\n{\n    \"employee\": {\n        \"firstName\": \"Raghavan\",\n        \"lastName\": \"Muthu\",\n        \"age\": 35,\n        \"country\": \"India\",\n        \"department\": \"Technology\",\n        \"project\": {\n            \"name\": \"Payroll Automation\",\n            \"manager\": \"Mark\"\n        }\n    }\n}\n\nIndividual Attributes\n---------------------\nJSONObject employee firstName : Raghavan\nJSONObject employee age : 35\nJSONObject employee project name : Payroll Automation\n\n<\/pre>\n<h3>3.7. Creating JSON data via JSONBuilder from POGO<\/h3>\n<p><code>JsonBuilder<\/code> class helps you to generate JSON from the Java objects. It is the reverse of <code>JsonSlurper<\/code> which reads and parses to get you the JSON Object.[ulp id=&#8217;kHqyxwGNoyzYAfPN&#8217;]<\/p>\n<p>We use JsonBuilder to generate a JSON specific data that can be either written to a file, for example configuration files for an application, or to a different URL source via a suitable <code><em>java.io.Writer<\/em><\/code> Implementation class.<\/p>\n<p>The advantage and specialty of the JsonBuilder class is that you can very easily construct an object by specifying the members and their values in a literal String, without actually creating an instance of a separate POGO class. That is you can build your object at runtime. This way it is very helpful to create configuration classes which are JSON specific.<\/p>\n<p>In the below example, the code snippet shows two parts &#8211; first generating a JSON object on the fly using the JsonBuilder and then parsing it into a Java object via JsonSlurper for manipulating its properties one by one.<\/p>\n<p><span style=\"text-decoration: underline\"><em>JsonBuilder1Basic.groovy<\/em><\/span><\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.example.groovy.json;\n\nimport groovy.json.JsonBuilder\nimport groovy.json.JsonSlurper\n\n\/\/ Part 1 - Create a JSON content on the fly using JsonBuilder \n\ndef builder = new JsonBuilder()\nbuilder.book {\n    title 'Head First Java'\n    publisher 'Orielly'\n    author 'Kathy Sierra', 'Bert Bates'\n    year '2005'\n    currency 'USD'\n    price 44.95\n    format 'pdf', 'print'\n}\n\nprintln builder\nprintln \"\"\nprintln builder.toPrettyString()\n\n\/* Part 2 - Parse the Json Content into a JSON Object via JsonSlurper for further usage *\/\n\ndef jsonSlurper = new JsonSlurper()\ndef jsonBookObj = jsonSlurper.parseText(builder.toString())\n\nprintln \"JsonBook Object : \" \nprintln jsonBookObj\nprintln \"JsonBook Object type : \" + jsonBookObj.getClass()\nprintln \"JsonBook Object size : \" + jsonBookObj.size()\nprintln \"\"\n\ndef book = jsonBookObj.book\nprintln \"Book Instance : \" \nprintln jsonBookObj.book\nprintln \"Book Instance Type : \" + book.getClass()\nprintln \"Book Instance size : \" + jsonBookObj.book.size()\nprintln \"\"\nprintln \"Individual Attributes\"\nprintln \"----------------------\"\nprintln \"Title : \" +  jsonBookObj.book.title + \" || Type : \" + book.title.getClass()\nprintln \"Author : \" + book.author + \" || Type : \" + book.author.getClass() + \" || Size : \" + book.author.size\nprintln \"Price : \" + book.price + \" || Type : \" + book.price.getClass()\nprintln \"Currency : \" + book.currency +  \" || Type : \" + book.currency.getClass()\nprintln \"Format : \" + book.format +  \" || Type : \" + book.format.getClass() + \" || Size : \" + book.format.size\n\n<\/pre>\n<p>The above script produces the following output.<\/p>\n<pre class=\"brush:java\">{\"book\":{\"title\":\"Head First Java\",\"publisher\":\"Orielly\",\"author\":[\"Kathy Sierra\",\"Bert Bates\"],\"year\":\"2005\",\"currency\":\"USD\",\"price\":44.95,\"format\":[\"pdf\",\"print\"]}}\n\n{\n    \"book\": {\n        \"title\": \"Head First Java\",\n        \"publisher\": \"Orielly\",\n        \"author\": [\n            \"Kathy Sierra\",\n            \"Bert Bates\"\n        ],\n        \"year\": \"2005\",\n        \"currency\": \"USD\",\n        \"price\": 44.95,\n        \"format\": [\n            \"pdf\",\n            \"print\"\n        ]\n    }\n}\nJsonBook Object : \n[book:[author:[Kathy Sierra, Bert Bates], currency:USD, format:[pdf, print], price:44.95, publisher:Orielly, title:Head First Java, year:2005]]\nJsonBook Object type : class groovy.json.internal.LazyMap\nJsonBook Object size : 1\n\nBook Instance : \n[author:[Kathy Sierra, Bert Bates], currency:USD, format:[pdf, print], price:44.95, publisher:Orielly, title:Head First Java, year:2005]\nBook Instance Type : class groovy.json.internal.LazyMap\nBook Instance size : 7\n\nIndividual Attributes\n----------------------\nTitle : Head First Java || Type : class java.lang.String\nAuthor : [Kathy Sierra, Bert Bates] || Type : class java.util.ArrayList || Size : 2\nPrice : 44.95 || Type : class java.math.BigDecimal\nCurrency : USD || Type : class java.lang.String\nFormat : [pdf, print] || Type : class java.util.ArrayList || Size : 2\n\n<\/pre>\n<h3>3.8. Creating JSON data via JSONBuilder and Write to a File<\/h3>\n<p>In this example, we will see how we can generate the JSON data using the <code>JsonBuilder<\/code> and use its API method to write the JSON into a file in the disk.<\/p>\n<p>This will be handy when we need to write our JSON specific configuration into a file which can later be read by a Container for serving our application to users.<\/p>\n<p>In this example will write the contents into a file and subsequently we will read the file contents and display for our verification.<\/p>\n<p><span style=\"text-decoration: underline\"><em>JsonBuilder2File.groovy<\/em><\/span><\/p>\n<pre class=\"brush:java\">package com.javacodegeeks.example.groovy.json;\n\nimport groovy.json.JsonBuilder\nimport groovy.json.JsonOutput\n\ndef jsonBuilder = new JsonBuilder()\n\njsonBuilder.config\n{\n    env : \"Prod\"\n    database {\n        host \"example.com\"\n        port 3306\n        type \"MySQL\"\n        user 'dbUser'\n        pass 'dbPass'\n        driver 'com.mysql.jdbc.Driver'\n    }\n    threadPool 10\n    useBridge 'Y'\n}\n\nprintln \"JSONBuilder Object : \" + jsonBuilder\nprintln \"\"\nprintln \"JSON Pretty Printed Config \"\nprintln \"==========================\"\nprintln JsonOutput.prettyPrint(jsonBuilder.toString())\nprintln \"\"\n\nString outputFile = 'config.json'\ndef fileWriter = new FileWriter(outputFile)\njsonBuilder.writeTo(fileWriter)\nfileWriter.flush() \/* to push the data from  buffer to file *\/\nprintln \"Config details are written into the file '${outputFile}'\"\n\nprintln \"\"\ndef fileContents = new File(outputFile).text\nprintln \"File contents : \" + fileContents\nprintln \"\"\nprintln \"File Contents PrettyPrint\"\nprintln \"=========================\"\nprintln JsonOutput.prettyPrint(fileContents)\n\n<\/pre>\n<p>The above script produces the following output.<\/p>\n<pre class=\"brush:java; wrap-lines:false\">JSONBuilder Object : {\"config\":{\"database\":{\"host\":\"example.com\",\"port\":3306,\"type\":\"MySQL\",\"user\":\"dbUser\",\"pass\":\"dbPass\",\"driver\":\"com.mysql.jdbc.Driver\"},\"threadPool\":10,\"useBridge\":\"Y\"}}\n\nJSON Pretty Printed Config \n==========================\n{\n    \"config\": {\n        \"database\": {\n            \"host\": \"example.com\",\n            \"port\": 3306,\n            \"type\": \"MySQL\",\n            \"user\": \"dbUser\",\n            \"pass\": \"dbPass\",\n            \"driver\": \"com.mysql.jdbc.Driver\"\n        },\n        \"threadPool\": 10,\n        \"useBridge\": \"Y\"\n    }\n}\n\nConfig details are written into the file 'config.json'\n\nFile contents : {\"config\":{\"database\":{\"host\":\"example.com\",\"port\":3306,\"type\":\"MySQL\",\"user\":\"dbUser\",\"pass\":\"dbPass\",\"driver\":\"com.mysql.jdbc.Driver\"},\"threadPool\":10,\"useBridge\":\"Y\"}}\n\nFile Contents PrettyPrint\n=========================\n{\n    \"config\": {\n        \"database\": {\n            \"host\": \"example.com\",\n            \"port\": 3306,\n            \"type\": \"MySQL\",\n            \"user\": \"dbUser\",\n            \"pass\": \"dbPass\",\n            \"driver\": \"com.mysql.jdbc.Driver\"\n        },\n        \"threadPool\": 10,\n        \"useBridge\": \"Y\"\n    }\n}\n\n\n<\/pre>\n<p>Hope you found this example series helpful in manipulating the JSON data with Groovy scripts, for the simple use cases. However if  you have a different (or advanced) scenario at hand, you are recommended to read the API for the variants of each class and its methods.<\/p>\n<h3>4. References<\/h3>\n<p>You may please refer the following URLs for further reading.<\/p>\n<ol>\n<li><a href=\"http:\/\/groovy-lang.org\/json.html\">Groovy Json from Groovy Language Documentation<\/a><\/li>\n<li><a href=\"http:\/\/docs.groovy-lang.org\/latest\/html\/gapi\/groovy\/json\/JsonSlurper.html\">JsonSlurper Groovy API<\/a><\/li>\n<li><a href=\"http:\/\/docs.groovy-lang.org\/latest\/html\/gapi\/groovy\/json\/JsonBuilder.html\">JsonBuilder Groovy API<\/a><\/li>\n<li><a href=\"http:\/\/docs.groovy-lang.org\/latest\/html\/gapi\/groovy\/json\/JsonOutput.html\">JsonOutput Groovy API<\/a><\/li>\n<\/ol>\n<h2>5. Download the Source Code<\/h2>\n<p>This is an example of how to read and write JSON data in Groovy, tested with the Command Prompt \/ Shell against Groovy Version 2.4.3.<\/p>\n<div class=\"download\"><strong>Download<\/strong><br \/>\nYou can download the full source code of this example here: <strong><a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/03\/groovy-json-example.zip\">Groovy JSON Example<\/a><\/strong><\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this article we will see how to manipulate JSON data in Groovy. JSON (JavaScript Object Notation) is the much preferred data format these days for the exchange of data between the interested parties (client and server), due to its light weight nature and ease of use. Groovy has a built in support to work &hellip;<\/p>\n","protected":false},"author":87,"featured_media":24987,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1216],"tags":[],"class_list":["post-34827","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-groovy"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Groovy Json Example - Java Code Geeks<\/title>\n<meta name=\"description\" content=\"In this article we will see how to manipulate JSON data in Groovy. JSON (JavaScript Object Notation) is the much preferred data format these days for the\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Groovy Json Example - Java Code Geeks\" \/>\n<meta property=\"og:description\" content=\"In this article we will see how to manipulate JSON data in Groovy. JSON (JavaScript Object Notation) is the much preferred data format these days for the\" \/>\n<meta property=\"og:url\" content=\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/\" \/>\n<meta property=\"og:site_name\" content=\"Examples Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2016-03-18T13:00:42+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2019-03-29T12:25:34+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/07\/groovy-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Raghavan Muthu\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/itsraghz\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Raghavan Muthu\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"13 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/\"},\"author\":{\"name\":\"Raghavan Muthu\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/aa8716fe8bdb3e382d5bdf9b9e960315\"},\"headline\":\"Groovy Json Example\",\"datePublished\":\"2016-03-18T13:00:42+00:00\",\"dateModified\":\"2019-03-29T12:25:34+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/\"},\"wordCount\":1381,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/07\/groovy-logo.jpg\",\"articleSection\":[\"Groovy\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/\",\"name\":\"Groovy Json Example - Java Code Geeks\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/07\/groovy-logo.jpg\",\"datePublished\":\"2016-03-18T13:00:42+00:00\",\"dateModified\":\"2019-03-29T12:25:34+00:00\",\"description\":\"In this article we will see how to manipulate JSON data in Groovy. JSON (JavaScript Object Notation) is the much preferred data format these days for the\",\"breadcrumb\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/#primaryimage\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/07\/groovy-logo.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/07\/groovy-logo.jpg\",\"width\":150,\"height\":150},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/examples.javacodegeeks.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"JVM Languages\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/jvm-languages\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Groovy\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/jvm-languages\/groovy\/\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"Groovy Json Example\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Examples and Code Snippets\",\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/javacodegeeks\",\"https:\/\/x.com\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/aa8716fe8bdb3e382d5bdf9b9e960315\",\"name\":\"Raghavan Muthu\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/01\/Raghavan-Muthu-96x96.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/01\/Raghavan-Muthu-96x96.jpg\",\"caption\":\"Raghavan Muthu\"},\"description\":\"Raghavan alias Saravanan Muthu is a seasoned IT professional having more than 2 decades of experience on Java SE\/EE based Application Architecture, Design, Development, Management and Administration for Banking, Insurance, Telecom, HealthCare and Automobile Industries, having a very good hands on experience on Multi-threaded, batch processing applications and Relational Databases. He is currently working as a Director of Engineering for one of the Product based companies in India that delivers the product on Health Care and Insurance Domain. He holds a Post Graduation (Master of Science), and a PG Degree on Big Data Engineering from Birla Institute of Technology and Science (BITS), Pilani, India. He is a Founder, Chief Executive Volunteer and a Web Master of a non-profit charity organization named SHaDE (http:\/\/shade.org.in).\",\"sameAs\":[\"https:\/\/www.raghsonline.com\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/itsraghz\"],\"url\":\"https:\/\/examples.javacodegeeks.com\/author\/raghavan-muthu\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Groovy Json Example - Java Code Geeks","description":"In this article we will see how to manipulate JSON data in Groovy. JSON (JavaScript Object Notation) is the much preferred data format these days for the","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/","og_locale":"en_US","og_type":"article","og_title":"Groovy Json Example - Java Code Geeks","og_description":"In this article we will see how to manipulate JSON data in Groovy. JSON (JavaScript Object Notation) is the much preferred data format these days for the","og_url":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/","og_site_name":"Examples Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_published_time":"2016-03-18T13:00:42+00:00","article_modified_time":"2019-03-29T12:25:34+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/07\/groovy-logo.jpg","type":"image\/jpeg"}],"author":"Raghavan Muthu","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/itsraghz","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Raghavan Muthu","Est. reading time":"13 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/#article","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/"},"author":{"name":"Raghavan Muthu","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/aa8716fe8bdb3e382d5bdf9b9e960315"},"headline":"Groovy Json Example","datePublished":"2016-03-18T13:00:42+00:00","dateModified":"2019-03-29T12:25:34+00:00","mainEntityOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/"},"wordCount":1381,"commentCount":0,"publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/07\/groovy-logo.jpg","articleSection":["Groovy"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/","url":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/","name":"Groovy Json Example - Java Code Geeks","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/#primaryimage"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/07\/groovy-logo.jpg","datePublished":"2016-03-18T13:00:42+00:00","dateModified":"2019-03-29T12:25:34+00:00","description":"In this article we will see how to manipulate JSON data in Groovy. JSON (JavaScript Object Notation) is the much preferred data format these days for the","breadcrumb":{"@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/#primaryimage","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/07\/groovy-logo.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2015\/07\/groovy-logo.jpg","width":150,"height":150},{"@type":"BreadcrumbList","@id":"https:\/\/examples.javacodegeeks.com\/jvm-languages\/groovy\/groovy-json-example\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/examples.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"JVM Languages","item":"https:\/\/examples.javacodegeeks.com\/category\/jvm-languages\/"},{"@type":"ListItem","position":3,"name":"Groovy","item":"https:\/\/examples.javacodegeeks.com\/category\/jvm-languages\/groovy\/"},{"@type":"ListItem","position":4,"name":"Groovy Json Example"}]},{"@type":"WebSite","@id":"https:\/\/examples.javacodegeeks.com\/#website","url":"https:\/\/examples.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/examples.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/examples.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/aa8716fe8bdb3e382d5bdf9b9e960315","name":"Raghavan Muthu","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/01\/Raghavan-Muthu-96x96.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/01\/Raghavan-Muthu-96x96.jpg","caption":"Raghavan Muthu"},"description":"Raghavan alias Saravanan Muthu is a seasoned IT professional having more than 2 decades of experience on Java SE\/EE based Application Architecture, Design, Development, Management and Administration for Banking, Insurance, Telecom, HealthCare and Automobile Industries, having a very good hands on experience on Multi-threaded, batch processing applications and Relational Databases. He is currently working as a Director of Engineering for one of the Product based companies in India that delivers the product on Health Care and Insurance Domain. He holds a Post Graduation (Master of Science), and a PG Degree on Big Data Engineering from Birla Institute of Technology and Science (BITS), Pilani, India. He is a Founder, Chief Executive Volunteer and a Web Master of a non-profit charity organization named SHaDE (http:\/\/shade.org.in).","sameAs":["https:\/\/www.raghsonline.com\/","https:\/\/x.com\/https:\/\/twitter.com\/itsraghz"],"url":"https:\/\/examples.javacodegeeks.com\/author\/raghavan-muthu\/"}]}},"_links":{"self":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/34827","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/users\/87"}],"replies":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=34827"}],"version-history":[{"count":0,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/34827\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media\/24987"}],"wp:attachment":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=34827"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=34827"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=34827"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}