I have a Grails controller action that return a JSON object
def someAction(String customerParameter) {
JsonBuilder json = new JsonBuilder()
def jsonObject = json {
someAttribute "someValue"
} as JSON
// TODO: if customerParamter is not null add it to json object
render (contentType: 'application/json;charset=UTF-8', text:json)
}
As the above code mentioned, I'd like to modify the json object without rebuilding it with or without the given customerParameter.
Well, I found a solution using the "content" property:
if (customerParameter) {
json.content << ["custmoerParameter": customerParameter]
}
Related
I have a JSON Object as below:
{
"_embedded":{
"user":{
"passwordChanged":"01/10/2017",
"profile":{
"firstName":"xyz",
"lastName":"abc",
"timeZone":"America/Los_Angeles",
"login":"xyz#abc.com",
"locale":"en"
},
"id":"1234567a"
}
},
"token":"120392w",
"expiresAt":"01/12/2022",
"status":"active"
}
I want to iterate this object and retrieve the value of "timeZone". How do I do it in JAVA?
Use gson to parse the json to a class:
Gson gson = new GsonBuilder.create();
UserData userData = gson.fromJson("your json here",UserData.class);
System.out.println(userData.get_embeded().getUser().getProfile().getTimeZone());
Note that you'll have to create the class you are parsing the json to.
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 use http4s and scalaz.steam._
def usersService = HttpService{
case req # POST -> Root / "check" / IntVar(userId) =>{
//val jsonobj=parse(req.as[String])
val taskAsJson:String = write[req.body]
Ok(read[Task](taskAsJson))
}
}
For http4s, the request can get body as the type Process[Task, ByteVector]
The Process is scalaz.stream.process class. You can find details on scalaz.
I want to write a Task here can deal with JSON ByteVector and translate into a Map (like HashMap), layer by layer.
I mean, for example:
{
"id":"12589",
"customers":[{
"id": "898970",
"name":"Frank"
...
},
]
}
I do not know how to write the function via scalaz.stream.Process to change the JSON to mapobject.
I want response and to parse the JSON object, returning another refactored JSON object; how can I do it?
I'm new to grails, the problem i'm trying to solve is pretty simple : my server should receive some json data in a request validate the data and save it to a DB.
To my best understanding I use Command Object to validate the data. the problem is that if my Command object contains a list of another class ( a secondary command object ) the parser would put in that field a jsonArray and this would ignore my secondary validation.
Parsing json ->
void handleRequest(){
def jsonObject = request.JSON
doSomething(new PrimaryCommandObject(jsonObject))
}
def doSomething(PrimaryCommandObject cmd){
if (cmd.validate()) {
respond cmd
}else{
cmd.errors.allErrors.each {
println it
}
}
}
Main Command object ->
class PrimaryCommandObject{
int val1
List<SecondaryCommandObject> collection
}
Right now in order to bypass this issue I added a setter
Setter ->
void setCollection(JSONArray jsonArray){
this.collection = []
jsonArray.each { item ->
SecondaryCommandObject obj = item as SecondaryCommandObject
if (obj.validate()) {
this.collection << obj
}else {
obj.errors.allErrors.each {
println it
}
}
}
This doesn't feel right for me, I would except a cleaner simpler way to get it done. this
can someone please help ? thanks
I have the below JSON string coming in as a request parameter into my grails controller.
{
"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"
}
As you can see, the timesheetList might have multiple elements in it. In this ( above ) case, we have only one. So, I expect it to behave like an Array/List.
Then I had the below code to parse through it:
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 timesheet1 = 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. Any help?
1st off to simplify your code, use request.JSON. Then request.JSON.list[ 0 ] should be working