Rendering few models in gson - grails

Is it possible to send few objects into gson rendering view?
I tried to use in controller:
respond trainings, [status: OK, view:"trainingsByClients", model: [myVariable: "test", anotherVariable: 123]]
and in gson view:
model {
Iterable<Training> trainingList
String myVariable
}
json {
myVariable myVariable
trainings tmpl.training(trainingList ?: [])
}
and it responds with:
{
"myVariable": null,
"trainings": [
{
"id": 3,
"name": "test t",
"numberOfAbsentClients": 0,
"startDate": "2016-11-20T09:00:00+0000",
"numberOfClients": 2,
"section": {
"id": 1,
"name": "test sec"
}
},
{
"id": 10,
"name": "test 2",
"numberOfAbsentClients": 0,
"startDate": "2016-11-09T11:00:00+0000",
"numberOfClients": 2,
"section": {
"id": 2,
"name": "sec 2"
}
}
]
}

ok, I found solution:
render(view: "trainingsByClients", model: [trainingList: trainings, myVariable: "asdg"])
so we should use render instead of respond. Respond is not adding properly additional model objects.

Actually you have to use the g.render method for all model properties when using respond
example gson view:
model {
Iterable<Training> trainingList
String myVariable
}
json {
myVariable g.render(myVariable)
trainings tmpl.training(trainingList ?: [])
}
This is only related to the models you parse in the respond.model parameter

Related

get parent object filter by nested child fields

Inside teacher, there is child subject, and subject has a child student. I want to get all teachers filter by student_name. Teacher object can be something like this:
{ "id": 5,
"name": "teacher-one",
"gender": "male",
"subject": {
"id": 10,
"subject_name": "Maths",
"student": {
"id": 1,
"student_name": "student-one",
"grade" : "one",
}
}
}
I am looking to filter this out by using find method, something like
Teacher.find(:all, params: {gender: "male'}) which returns all the male teachers. But the following code does not work:
Teacher.find(:all, params: { subject: { student: grade == "one" }})
Try this:
Teacher.joins(subject: :student).where(student: {student_name: "Bala"})

Get key of dictionary on JSON parse with SwiftyJSON

I want to get "key of dictionary" (that's what I called, not sure if it is right name) on this JSON
{
"People": {
"People with nice hair": {
"name": "Peter John",
"age": 12,
"books": [
{
"title": "Breaking Bad",
"release": "2011"
},
{
"title": "Twilight",
"release": "2012"
},
{
"title": "Gone Wild",
"release": "2013"
}
]
},
"People with jacket": {
"name": "Jason Bourne",
"age": 15,
"books": [
{
"title": "Breaking Bad",
"release": "2011"
},
{
"title": "Twilight",
"release": "2012"
},
{
"title": "Gone Wild",
"release": "2013"
}
]
}
}
}
First of all, I already created my People struct that will be used to map from those JSON.
Here is my people struct
struct People {
var peopleLooks:String?
var name:String?
var books = [Book]()
}
And here is my Book struct
struct Book {
var title:String?
var release:String?
}
From that JSON, I created engine with Alamofire and SwiftyJSON that will be called in my controller via completion handler
Alamofire.request(request).responseJSON { response in
if response.result.error == nil {
let json = JSON(response.result.value!)
success(json)
}
}
And here is what I do in my controller
Engine.instance.getPeople(request, success:(JSON?)->void),
success:{ (json) in
// getting all the json object
let jsonRecieve = JSON((json?.dictionaryObject)!)
// get list of people
let peoples = jsonRecieve["People"]
// from here, we try to map people into our struct that I don't know how.
}
My question is, how to map my peoples from jsonRecieve["People"] into my struct?
I want "People with nice hair" as a value of peopleLooks on my People struct. I thought "People with nice hair" is kind of key of dictionary or something, but I don't know how to get that.
Any help would be appreciated. Thank you!
While you iterate through dictionaries, for instance
for peeps in peoples
You can access key with
peeps.0
and value with
peeps.1
You can use key, value loop.
for (key,subJson):(String, JSON) in json["People"] {
// you can use key and subJson here.
}

Rails 4 - Iterate through nested JSON params

I'm passing nested JSON into rails like so:
{
"product": {
"vendor": "Acme",
"categories":
{
"id": "3",
"method": "remove",
},
"categories":
{
"id": "4"
}
}
}
in order to update the category on a product. I am trying to iterate through the categories attribute in my products_controller so that I can add/remove the product to multiple categories at once:
def updateCategory
#product = Product.find(params[:id])
params[:product][:categories].each do |u|
#category = Category.find_by(id: params[:product][:categories][:id])
if params[:product][:categories][:method] == "remove"
#product.remove_from_category(#category)
else
#product.add_to_category(#category)
end
end
end
However, this only uses the second 'categories' ID in the update and doesn't iterate through both.
Example response JSON:
{
"product": {
"id": 20,
"title": "Heavy Duty Aluminum Chair",
"product_price": "47.47",
"vendor": "Acme",
"categories": [
{
"id": 4,
"title": "Category 4"
}
]
}
}
As you can see, it only added the category with ID = 4, and skipped over Category 3.
I'm fairly new to rails so I know I'm probably missing something obvious here. I've played around with the format of the JSON I'm passing in as well but it only made things worse.
You need to change your JSON structure. As you currently have it, the second "categories" reference will override the first one since you can only have 1 instance of a key. To get what you want, you should change it to:
{
"product": {
"vendor": "Acme",
"categories": [
{
"id": "3",
"method": "remove",
},
{
"id": "4"
}
]
}
}
You will also need to change your ruby code to look like:
def updateCategory
#product = Product.find(params[:id])
params[:product][:categories].each do |u|
#category = Category.find_by(id: u[:id])
if u[:method] == "remove"
#product.remove_from_category(#category)
else
#product.add_to_category(#category)
end
end
end

Swift 3 looping JSON data

I'm attempting to loop through a JSON array sending data to a struct.
Here's my code that uses SwiftyJSON to return a JSON object:
performAPICall() {
json in
if(json != nil){
print("Here is the JSON:")
print(json["content"]["clients"])
let clients = json["content"]["clients"]
for client in clients {
var thisClient = Client()
thisClient.id = client["id"].string
thisClient.desc = client["desc"].string
thisClient.name = client["name"].string
self.clientArray.append(thisClient)
}
self.tableView.reloadData()
} else {
print("Something went very wrong..,")
}
}
I'm not quite sure why I'm getting "has no subscript" errors on the three strings.
Any help appreciated, thanks.
EDIT: Here's a sample of the JSON
{
"content": {
"clients": [{
"group": "client",
"id": "group_8oefXvIRV4",
"name": "John Doe",
"desc": "John's group."
}, {
"group": "client",
"id": "group_hVqIc1eEsZ",
"name": "Demo Client One",
"desc": "Demo Client One's description! "
}, {
"group": "client",
"id": "group_Yb0vvlscci",
"name": "Demo Client Two",
"desc": "This is Demo Client Two's group"
}]
}
}
You should use array method. Thus, your line
let clients = json["content"]["clients"]
should use array (and unwrap it safely):
guard let clients = json["content"]["clients"].array else {
print("didn't find content/clients")
return
}
// proceed with `for` loop here

How do I design a ruby equivalent objects for this json structure

I have a json structure that I need to build up based on url parameters provided by a client. Currently I've been building the json structure out using Jbuilder.encode but it's getting pretty hairy.
self.query = Jbuilder.encode do |json|
json.query do
json.filtered do
json.filter do
json.bool do
if(search_term && username)
json.array!(should) do
........
How can I build ruby objects so that I convert them into json based on how they are initialized?
Below is the full json structure I'd like to capture in ruby models/poros (plain old ruby objects).
{
"query": {
"filtered": {
"filter": {
"bool": {
"should": [
{
"query": {
"query_string": {
"query": "tablet",
"fields": [
"standard_analyzed_name",
"standard_analyzed_message"
]
}
}
},
{
"term": {
"username": "feedmatic"
}
}
],
"must": [
{
"terms": {
"status_type": [
"3",
"4"
]
}
},
{
"range": {
"created_on": {
"gte": 20140712,
"lte": 1405134711
}
}
}
]
}
}
}
}
}
Hmm i'm not really sure about Poro's, but one thing I've seen is that when the structure starts to get hairy is to make a method that returns the hash representation of what you would like to show. Have you tried making a query method that returns a hash with that structure and then calling it in a jbuilder template?
There's an .attributes method for rails that returns a hash with the attributes, but you would have to look into how to use it with a PORO and if it works for this purpose.

Resources