I've seen countless examples of JsonSlurper used to parse JSON text and create a "JSON object" out of it:
def jsonObject = jsonSlurper.parseText(jsonText)
But what if the JSON text represent one of my FizzBuzz objects? Can I use JsonSlurper to map the JSON object into a FizzBuzz instance? If so, how?
After parsing JSON with JsonSlurper You receive a Map. If FizzBuzz has a Map (see here) constructor it should work when parsed Map is passed to constructor.
See the following example:
import groovy.json.JsonSlurper
def json = """{ "name": "John", "age": 127 }"""
def parsed = new JsonSlurper().parseText(json)
def person = parsed as Person
assert person.age == 127
assert person.name == 'John'
class Person {
String name
int age
}
Related
Seeing an interesting issue, not sure this is to do with parser or the way it suppose to parse. Any help is appreciated
import groovy.json.JsonSlurper
def dMatch = '''[{"match":{"keyId":"A-102161-application"}},{"match":{"keyId":"A-102162-application"}},{"match":{"keyId":"A-102163-application"}},{"match":{"keyId":"A-102164-application"}},{"match":{"keyId":"A-102165-application"}}]'''
println "T1:: List: " + dMatch
def parser = new JsonSlurper()
def exclude = parser.parseText(dMatch)
println "T2:: Obj: " + exclude.toString()
println "----------------------------------------------------"
Output :
T1:: List: [{"match":{"keyId":"A-102161-application"}},
{"match":{"keyId":"A-102162-application"}},
{"match":{"keyId":"A-102163-application"}},
{"match":{"keyId":"A-102164-application"}},
{"match":{"keyId":"A-102165-application"}}]
T2:: Obj: *[[match:[keyId:A-102161-application]],
[match:[keyId:A-102162-application]],
[match:[keyId:A-102163-application]],
[match:[keyId:A-102164-application]],
[match:[keyId:A-102165-application]]]*
The parsed object supposed to be same as the string but all the values were converted as array list of map.
Any idea why this is generating object like this ? When this is sent to camunda it complains
org.camunda.bpm.engine.ProcessEngineException: Cannot serialize object in variable 'exclude': groovy.json.internal.LazyMap
Use JsonSlurperClassic() - it produces standard HashMap that is serializable.
And if you want to convert object back to json use Json output.toJson(obj)
I have 2 JSON files and I want to merge those 2 and create one JSON message using groovy. Based on the "type" value I'm going to merge those two JSON files.
If the given "type" of JSON objects of JSON message 1 does not exist
in the JSON message2, the relevant JSON object should be contained in the output JSON message.
All the JSON objects from JSON message2 should be contained in the
output JSON message
Expected sample formats is shown below
Input JSON message1
{"message":[{"name":"HelloFile","type": "input"},{"name":"SecondFile","type": "error"}]
Input JSON message2
[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"}]
Expected JSON
{"message":[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"},{"name":"SecondFile","type": "error"}]}
I used the below groovy code.
JsonBuilder jsonBuilder = new JsonBuilder(JSON1)
jsonBuilder.content.message= JSON2
def updatedBody = jsonBuilder.toString()
From the above code, I got the below message.
{"message":[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"}]}
Any help sorting this would be much appreciated.
Try using JsonSlurper:
import groovy.json.*
def json1 = '{"message":[{"name":"HelloFile","type": "input"},{"name":"SecondFile","type": "error"}]}'
def json2 = '[{"name":"NewFile","type": "input"},{"name":"MyFile","type": "output"}]'
def slurper = new JsonSlurper()
def json1Obj = slurper.parseText(json1)
def json2Obj = slurper.parseText(json2)
json1Obj.message+=json2Obj
println JsonOutput.toJson(json1Obj)
This prints:
{"message":[{"name":"HelloFile","type":"input"},{"name":"SecondFile","type":"error"},{"name":"NewFile","type":"input"},{"name":"MyFile","type":"output"}]}
I need to find json response length. Sample response looks like below:
{
"resource": {
"name":"aaaaaaaaaaa",
"emailid":"bbbbbbbbb"
}
}
As two parameters are present in resource. So, i should have got response as 2.
Please let me know hoe i can find json length as 2
This is the working solution, try this
import groovy.json.JsonSlurper // import this class
def jsonText = '''{
"resource": {
"name":"aaaaaaaaaaa",
"emailid":"bbbbbbbbb"
}
}'''
def json = new JsonSlurper().parseText(jsonText)
println "Json length---------->"+json.resource.size()
If you have the JSON object, you don't need to parse JSON string to json, yo can directly do the following,
println jsonObject.resource.size() // Here resource is the key(sub node) inside your json
If you want to get the length of parent JSON key, just do as follows,
println jsonObject.size()
Based on your question, it appears that you would like to know the count of properties within a JSON object. So we can do that by following these steps:
STEP 1 : Parse the response string into JSON object
STEP 2 : Convert JSON object into groovy Map object
Step 3 : Call size() method on Map object to get the elements count within the map object
So your code would like this :
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def response = jsonSlurper.parseText('{ "resource": {"name":"aaaaaaaaaaa","emailid":"bbbbbbbbb"}}')
def object = (Map)response.resource
log.info object.size()
So your output will be 2. You can try adding more elements to JSON object check if it works.
Hope this helps :)
I have JSON that needs to be processed using Groovy. I am pretty sure that the JSON has only one key, with this format:
{ rootKey: [...] }
Where rootKey stands for different values (e.g. "customers", "stores", etc.).
Let's say I used JsonSlurper:
def map = jsonSlurper.parseText(myjson)
How do I obtain that rootKey string?
You should be able to use keySet method to get the keys which is a list. Since, you mentioned only key, you can use the first element as shown below:
def jsonString = """{
"rootKey": []
}"""
def json = new groovy.json.JsonSlurper().parseText(jsonString)
println json.keySet()[0]
I have a json that is displayed as below:
{
"rating": "5"
}
I have done an assertion that the value for 'rating' is not null, but I want to add another assertion that the DTO "rating" exists. How can this be done with script assertion is SOAP UI?
import com.eviware.soapui.support.GroovyUtils
import groovy.json.JsonSlurper
def response = messageExchange.response.responseContent
def json = new JsonSlurper().parseText(response)
def rating = json.rating
assert json.rating != null
assert json.containsKey('rating')
the class of json object in groovy:
http://docs.groovy-lang.org/2.4.7/html/gapi/groovy/json/internal/LazyMap.html