Replacing a number variable in json using groovy - json

I have a json which has some numbers that I want to make dynamic and replace the value using groovy. Please let me know if there is a better way as I have already used toInteger to convert but not working.
For ex
{
jobName:"",
protocolName:"tcp",
portNo:""
}
I am able to replace the job-name which is string using replace in groovy but I am not able to replace the port number. The final json should look like below
{
jobName:"myjob",
protocolName:"tcp",
portNo:1112
}
Please let me know if there is a way to do that in groovy

Something like this:
String str = '{ "jobName":"", "protocolName":"tcp", "portNo":"" }'
def json = new JsonSlurper().parseText(str)
json.jobName = 'myJob'
json.portNo = 1112
println new JsonOutput().prettyPrint(new JsonOutput().toJson(json))

Related

Kotlin: JSON string with linebreaker and variable

I would like to add linebreakers to a JSON string so it will be more readable.
val myString = "some string"
val myObjectJson = `
{
"example1": "value",
"example2": $myString
}`
So later I can use ObjectMapper to create an object. objectMapper.readValue(myObjectJson, MyClass::class.Java)
What I'm trying to figure out:
How to add lineBreaker in Json string?
Tried template literals:"`", doesn't seem to work in Kotline. gives Expecting an expression error.
How to use variable in Json string?
This might go away after I figure out how to add linebreakers.
(Edited because I think I have misunderstood your question).
Are you asking how to lay out a JSON string in the source code? If so then what you are looking for is the Raw String feature implemented with 3 double-quotes like this:
val myObjectJson = """
{
"example1": "value",
"example2": $myString
}
"""
But in case you asking
How to add lineBreaker in Json string?
(Assuming you are using Jackson's ObjectMapper)
Simply use writerWithDefaultPrettyPrinter() like this: MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(value)
If that is not good enough for you I suppose you could implement a custom Pretty Printer: https://www.javadoc.io/static/com.fasterxml.jackson.core/jackson-core/2.14.2/com/fasterxml/jackson/core/PrettyPrinter.html

Need help on Groovy Script

I am trying to remove double quotes from the Value of 'version' but, not able to do that with the following groovy codes. Please help me resolving this.
Source JSON:
{"version":"1",
"code":'',
"eccQuoteExternalQuoteId":'100000136',
"reasonForRejection":'',
"rejectionCode":'',
"state":{"code":'SOX_APP',"integrationKey":'Approve'},
"integrationKey":''}
Groovy Script:
def Message processData(Message message) {
//Body
def body = message.getBody(String.class);
def jsonSlurper = new JsonSlurper()
def list = jsonSlurper.parseText(body)
list.each{
it.version=Integer.parseInt(it.get("version").toString().replace(" ",""));
}
def jsonOP = JsonOutput.toJson(list)
message.setBody(jsonOP)
return message;
}
Replace
it.version=Integer.parseInt(it.get("version").toString().replace(" ",""));
with
it.version=it.get("version").toString().toInteger();
see the ref toInteger.
Your json is incorrect because there are single quotes used for some values. However you could try LAX parser to ignore this issue.
def jsonSlurper = new JsonSlurper().setType(JsonParserType.LAX)
If the json from question is coming through the message body then just change
list.each{
it.version=Integer.parseInt(it.get("version").toString().replace(" ",""));
}
To
list.version = list.version as Integer
#daggett is right, you can do like he said.
It seems that the value of that object is a string, not a problem of quotes.
You can check the class of any the object with:
println(it.version.getClass())
if it's a string you can change it in various ways but if its a string you could simply use the below - I'm putting it in more lines just for better visibility but the result is the same as the inline from daggett
def newInt = it.version.toInteger()
it.version = newInt
There are other ways to do the same thing if you really need to convert it.
here a guide:
https://www.baeldung.com/groovy-convert-string-to-integer
Maybe changing the value from string to int in that class creating the JSON is the best way to go.

JsonSlurper parsing String containing Json into unexpected format

From a separate system I get a String parameter "messageJson" whose content is in the form:
{"agent1":"smith","agent2":"brown","agent3":{"agent3_1":"jones","agent3_2":"johnson"}}
To use it in my program I parse it with JsonSlurper.
def myJson = new JsonSlurper().parseText(messageJson)
But the resulting Json has the form:
[agent1:smith, agent2:brown, agent3:[agent3_1:jones, agent3_2:johnson]]
Note the square brackets and the lack of double quotes. How can I parse messageJson so that the original structure is kept?
Ok, thanks to the hint by cfrick, I was able to find a solution. In case anyone else has a similar problem, all I needed to do was using JsonOutput in the end to convert the map back to a Json
I.E. :
def myJson = new JsonSlurper().parseText(messageJson)
myJson << [agent4:"jane"]
def backToJson = JsonOutput.toJson(myJson)

extract a concrete part of a value from a Response to a new string Groovy script

I'm kinda new in groovy and I need help
I need to write a groovy script to transform or else extract a concrete value from a Json Response to a new string Groovy script.
and the groovy script I used is this one :
responseJson = testRunner.testCase.getTestStepByName("Test Scenario").getPropertyValue("response")
parsedResponse = slurper.parseText(responseJson)
log.info(parsedResponse["items"]["/ticket_id"])
My generated string response from the groovy script I use looks like this:
/ticket_id":"{\"isTodo\":false,\"items\":[[\"WhatIwantToExtract\",\"\",\"url.com:blablabla_qc_vpc-11:Machine:data-da-data\",timestamp]]}
The response is correct in fact but I just want to extract a piece of this
The data I wanted to extract is labeled above as " WhatIwantToExtract " without the commas.
I solved it
def regexResult = (parsedResponse["items"][0][0])

Grails: Easy and efficient way to parse JSON from a Request

Please pardon me if this is a repeat question. I have been through some of the questions/answers with a similar requirement but somehow got a bit overwhelmed and confused at the same time. My requirement is:
I get a JSON string/object as a request parameter. ( eg: params.timesheetJSON )
I then have to parse/iterate through it.
Here is the JSON that my grails controller will be receiving:
{
"loginName":"user1",
"timesheetList":
[
{
"periodBegin":"2014/10/12",
"periodEnd":"2014/10/18",
"timesheetRows":[
{
"task":"Cleaning",
"description":"cleaning description",
"paycode":"payCode1"
},
{
"task":"painting",
"activityDescription":"painting description",
"paycode":"payCode2"
}
]
}
],
"overallStatus":"SUCCESS"
}
Questions:
How can I retrieve the whole JSON string from the request? Does request.JSON be fine here? If so, will request.JSON.timesheetJSON yield me the actual JSON that I want as a JSONObject?
What is the best way to parse through the JSON object that I got from the request? Is it grails.converters.JSON? Or is there any other easy way of parsing through? Like some API which will return the JSON as a collection of objects by automatically taking care of parsing. Or is programatically parsing through the JSON object the only way?
Like I said, please pardon me if the question is sounding vague. Any good references JSON parsing with grails might also be helpful here.
Edit: There's a change in the way I get the JSON string now. I get the JSON string as a request paramter.
String saveJSON // This holds the above JSON string.
def jsonObject = grails.converters.JSON.parse(saveJSON) // No problem here. Returns a JSONObject. I checked the class type.
def jsonArray = jsonArray.timesheetList // No problem here. Returns a JSONArray. I checked the class type.
println "*** Size of jsonArray1: " + jsonArray1.size() // Returns size 1. It seemed fine as the above JSON string had only one timesheet in timesheetList
def object1 = jsonArray[1] // This throws the JSONException, JSONArray[1] not found. I tried jsonArray.getJSONObject(1) and that throws the same exception.
Basically, I am looking to seamlessly iterate through the JSON string now.
I have wrote some code that explains how this can be done, that you can see below, but to be clear, first the answers to your questions:
Your JSON String as you wrote above will be the contents of your POST payload to the rest controller. Grails will use its data binding mechanism to bind the incomming data to a Command object that your should prepare. It has to have fields corresponding to the parameters in your JSON String (see below). After you bind your command object to your actual domain object, you can get all the data you want, by simply operating on fields and lists
The way to parse thru the JSON object is shown in my example below. The incomming request is esentially a nested map, with can be simply accessed with a dot
Now some code that illustrates how to do it.
In your controller create a method that accepts "YourCommand" object as input parameter:
def yourRestServiceMethod (YourCommand comm){
YourClass yourClass = new YourClass()
comm.bindTo(yourClass)
// do something with yourClass
// println yourClass.timeSheetList
}
The command looks like this:
class YourCommand {
String loginName
List<Map> timesheetList = []
String overallStatus
void bindTo(YourClass yourClass){
yourClass.loginName=loginName
yourClass.overallStatus=overallStatus
timesheetList.each { sheet ->
TimeSheet timeSheet = new TimeSheet()
timeSheet.periodBegin = sheet.periodBegin
timeSheet.periodEnd = sheet.periodEnd
sheet.timesheetRows.each { row ->
TimeSheetRow timeSheetRow = new TimeSheetRow()
timeSheetRow.task = row.task
timeSheetRow.description = row.description
timeSheetRow.paycode = row.paycode
timeSheet.timesheetRows.add(timeSheetRow)
}
yourClass.timeSheetList.add(timeSheet)
}
}
}
Its "bindTo" method is the key piece of logic that understands how to get parameters from the incomming request and map it to a regular object. That object is of type "YourClass" and it looks like this:
class YourClass {
String loginName
Collection<TimeSheet> timeSheetList = []
String overallStatus
}
all other classes that are part of that class:
class TimeSheet {
String periodBegin
String periodEnd
Collection<TimeSheetRow> timesheetRows = []
}
and the last one:
class TimeSheetRow {
String task
String description
String paycode
}
Hope this example is clear enough for you and answers your question
Edit: Extending the answer according to the new requirements
Looking at your new code, I see that you probably did some typos when writting that post
def jsonArray = jsonArray.timesheetList
should be:
def jsonArray = jsonObject.timesheetList
but you obviously have it properly in your code since otherwise it would not work, then the same with that line with "println":
jsonArray1.size()
shuold be:
jsonArray.size()
and the essential fix:
def object1 = jsonArray[1]
shuold be
def object1 = jsonArray[0]
your array is of size==1, the indexing starts with 0. // Can it be that easy? ;)
Then "object1" is again a JSONObject, so you can access the fields with a "." or as a map, for example like this:
object1.get('periodEnd')
I see your example contains errors, which lead you to implement more complex JSON parsing solutions.
I rewrite your sample to the working version. (At least now for Grails 3.x)
String saveJSON // This holds the above JSON string.
def jsonObject = grails.converters.JSON.parse(saveJSON)
println jsonObject.timesheetList // output timesheetList structure
println jsonObject.timesheetList[0].timesheetRows[1] // output second element of timesheetRows array: [paycode:payCode2, task:painting, activityDescription:painting description]