Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the exact json node instance using groovy?

Tags:

json

types

groovy

Input Json file :

{
   "menu": {
     "id": "file",
     "value": "File",
     "popup": {
          "menuitem": [
               {
                   "value": "New", 
                   "onclick": ["CreateNewDoc()","hai"],
                   "newnode":"added"
               }
          ]
      }
  }
}

Groovy code :

def newjson = new JsonSlurper().parse(new File ('/tmp/test.json'))
def value=newjson.menu.popup.menuitem.value
def oneclick=newjson.menu.popup.menuitem.onclick
println value
println value.class
println oneclick
println oneclick.class

Output:

[New]
class java.util.ArrayList
[[CreateNewDoc(), hai]]
class java.util.ArrayList

Here,
The json nodes which carries String and List returns the same class name with the groovy code above shown.

  • How can i differentiate that nodes value and oneclick. Logically I expect value should be a instance of String. but both returns as ArrayList.

  • How to get the exact type of node in json using groovy.

Update 1:

I don't exactly know, can do this like shown below. My expectation to get the results this,

New
class java.util.String
[CreateNewDoc(), hai]
class java.util.ArrayList
like image 518
Bhanuchander Udhayakumar Avatar asked Jun 23 '26 23:06

Bhanuchander Udhayakumar


2 Answers

Here you go:

  • In the below script using closure to show the details of each value and its type
  • Another closure is used to show the each map in the menuitem list.
def printDetails = { key, value -> println "Key - $key, its value is \"${value}\" and is of typpe ${value.class}" }

def showMap = { map -> map.collect { k, v -> printDetails (k,v) } }

def json = new groovy.json.JsonSlurper().parse(new File('/tmp/test.json'))
def mItem = json.menu.popup.menuitem
if (mItem instanceof List) {
   mItem.collect { showMap it  }
}
println 'done'

You can quickly try the same online demo

like image 68
Rao Avatar answered Jun 25 '26 21:06

Rao


menuitem is list, so you need to get property on concrete list element:

assert newjson.menu.popup.menuitem instanceof List
assert newjson.menu.popup.menuitem[0].value instanceof String
assert newjson.menu.popup.menuitem[0].onclick instanceof List
like image 26
Evgeny Smirnov Avatar answered Jun 25 '26 21:06

Evgeny Smirnov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!