JSON « Intelligrape Groovy & Grails Blogs

Posts Tagged ‘ JSON ’

JQuery: Send JSON Objects with an ajax request

Friday, June 11th, 2010
Posted by Amit Jain

Hi Friends,

Lets discuss today about sending JSON objects with ajax request using JQuery. We have number of functions in jQuery to kick-off an ajax request. But for sending JSON objects along with the request, I chose jQuer.ajax(). It takes various parameters url, type, data, dataType, beforeSend etc. Its API can be found here.

Lets look at example given below:

jQuery.ajax({
          url: <Url of the action>,
          type: "POST",
          data: {name: "amit", id:1 },
          dataType: "json",
          beforeSend: function(x) {
            if (x && x.overrideMimeType) {
              x.overrideMimeType("application/j-son;charset=UTF-8");
            }
          },
          success: function(result) {
 	     //Write your code here
          }
});

The above example works for simple JSON object. Now lets see how we can send JSON objects list as given below:

var jsonObjects = [{id:1, name:"amit"}, {id:2, name:"ankit"},{id:3, name:"atin"},{id:1, name:"puneet"}];
 
jQuery.ajax({
          url: <Url of the action>,
          type: "POST",
          data: {students: JSON.stringify(jsonObjects) },
          dataType: "json",
          beforeSend: function(x) {
            if (x && x.overrideMimeType) {
              x.overrideMimeType("application/j-son;charset=UTF-8");
            }
          },
          success: function(result) {
 	     //Write your code here
          }
});

If you notice, for sending my json objects it has not been written directly as data: jsonObjects. As it expects the JSON object passed to it written as key value pair. So we made students the key. And since we have json objects stored in a variable, we need to expand the json objects list using stringify(), otherwise it would be sent as a java script object.

Now on the server we can parse the JSON object, and use it as the list of objects of type map. For example

//this code is written in grails 
import grails.converters.JSON;
List<JSON> students = JSON.parse(params.students) //students in request params is parsed to json objects and stored in the List
println "Student id: " + students[0].studentId    //first element of the students list is accessed as a map holding a key studentId

Hope this helpled!

~~Amit Jain~~
amit@intelligrape.com

http://www.IntelliGrape.com

  • Share/Bookmark
Tags: , ,

Create JSON object Using Grails converter (Only selective fields from lists of objects)

Thursday, May 13th, 2010
Posted by salil

This post might help you if you want to get JSON (JavaScript Object Notation) Object on browser. Grails framework provides you very efficient way to achieve this.

For this you need to import grails JSON convertor in your code.

import grails.converters.JSON

Below is the code snapshot which converts java based lists of Objects to JSON object

HashMap jsonMap = new HashMap()
List<Company> companyList = Company.list()
List<Contact> employeeList = Employee.list()
 
jsonMap.companies = companyList.collect {comp ->
return [id: comp.id, name: comp.name, address: comp.address]
}
 
jsonMap.employees = employeeList.collect {emp ->
return [id: emp.id, name: emp.name, companyId: emp.companyId, role: emp.role]
}
 
render jsonMap as JSON

So you got it – MAGIC lies in “render jsonMap as JSON” statement.

Output sent to Browser:

{
  "companies": [
       {"id":281,"name":" Company Name Incorporated", "address": "street-address, zone-address, city, state, country, zip12"},
       {"id":282,"name":" Other company LLC", "address": "street-address1, zone-address2, city, state, country, zip34"},
  ],
  "employees": [
       {"id":123,"name":"Employee123 Name","companyId":281, "role":"Designer"},
       {"id":127,"name":"Employee127 Name","companyId":281, "role":"Supervisor"},
       {"id":129,"name":"Employee129 Name","companyId":282, "role":"Inspector"}
  ]
}

Isn’t it cool :-) . How to use JSON Objects on browser is out of scope of this post. I will try to write another post soon – how to query JSON based data to produce client-side results effectively (example – client side search).

Cheers!!
Salil Kalia

  • Share/Bookmark

How to use $.getJSON() method of jQuery with grails?

Monday, March 2nd, 2009
Posted by Chandan Luthra

How to use $.getJSON() method of jQuery with grails?

Retriving a JSON string from Grails is very easy. You have to just write the following in your controller’s action

Let me explain you with an example of populating a HTML table using JSON response:
In this example, we have table with columns – name,address and gender. We want the table to be populated without doing a full page refresh, using an Ajax call.

Domain Class:

class MyDomain {
    String name
    String address
    String gender
}

Controller Class :

class MyController {
   def someaction = {
      List myDomains = MyDomain.findAllByGender(params.gender)
      <em>/*Let say 5 objects are retrieved*/</em>
      render myDomains as JSON
   }
}

The above code in action will render a JSON string in the following format:

[
{
"name" : "John",
"address" : "New York",
"gender" : "Male"
},
{
"name" : "Rob",
"address" : "Indonasia",
"gender" : "Male"
},
{
"name" : "Shayam",
"address" : "New Delhi",
"gender" : "Male"
},
{
"name" : "Chang",
"address" : "Thailand",
"gender" : "Male"
},
{
"name" : "Ali",
"address" : "London",
"gender" : "Male"
}
]

following script would be writtent on the client Side (in the GSP):

<script>
$.document.ready(function(){
$('#someid').click(function(){
<strong>$.getJSON</strong>("${createLink(controller:'my',action:'someaction')}",{gender:'Male', ajax: 'true'}, function(myDomains){
var myHTMLString = ''
for(var i = 0 ; i < myDomains.length ; i++)
{
myHTMLString = myHTMLString + '<tr><td>' + myDomains[i].name + '</td>'
myHTMLString = myHTMLString + '<tr><td>' + myDomains[i].address + '</td>'
myHTMLString = myHTMLString + '<tr><td>' + myDomains[i].gender + '</td></tr>'
}
$('table#mytable').html(myHTMLString)
})
})
})
</script>

The HTML code would be like this :

<div id=”someid”>
Click for JSON Response
</div>
<table id=”mytable”>
<!–empty table –>
</table>

When you click on the displayed text the html page would become like following:

<div id="someid">
Click for JSON Response
</div>
<table id="mytable">
<tr>
<td>John</td>
<td>New York</td>
<td>Male</td>
</tr>
<tr>
<td>Rob</td>
<td>Indonasia</td>
<td>Male</td>
</tr>
<tr>
<td>Shayam</td>
<td>New Delhi</td>
<td>Male</td>
</tr>
<tr>
<td>Chang</td>
<td>Thailand</td>
<td>Male</td>
</tr>
<tr>
<td>Ali</td>
<td>London</td>
<td>Male</td>
</tr>
</table>

any kind of suggestions and comments are welcome……

Regards,
Chandan Luthra

http://www.IntelliGrape.com

  • Share/Bookmark