JSON
and Ajax with Jackson
Jackson
Sample
JSON data for a Student is like
{
“name”
: “Satya”
“age” : 21
}
·
Jackson
is a simple Java-based library to serialize Java objects to JSON and vice
versa.
·
Download
Jackson
Jars
·
To Convert JSON data to JavaObject we
use
Student
student= mapper.readValue(json_stu,
Student.class);
·
To Convert JavaObject data to JSON we
use
mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
String
json_stu = mapper.writeValueAsString(student);
|
1. ObjectMapper : class provides functionalities to convert
Java objects to matching JSON constructs and vice versa
2. readValue(Json_String, Bean.class) :
Converts JSON Data to Object Data
3. writeValueAsString(student);
Converts Object Data to JSON Data
Example:
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
import
org.codehaus.jackson.map.ObjectMapper;
import
org.codehaus.jackson.map.SerializationConfig;
public class JacksonMain {
public static void main(String[] args)
{
ObjectMapper mapper = new ObjectMapper();
String json_stu = "{\"name\":\"satya\",
\"age\":25}";
try {
Student student= mapper.readValue(json_stu, Student.class);
System.out.println("Student
Obejct :"+student);
System.out.println("Student
Obejct :"+student.getName());
System.out.println("Student
Obejct :"+student.getAge());
mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
json_stu = mapper.writeValueAsString(student);
System.out.println(json_stu);
} catch (Exception e) {
// TODO: handle exception
}
}
}
OUTPUT
Student Obejct
:xyz.Student@1516490
Student Obejct :satya
Student Obejct :21
{
"name" : "satya",
"age" : 21
}
Picked up
_JAVA_OPTIONS: -Djava.net.preferIPv4Stack=false
AJAX Basic
Simple
Ajax Syantax:
$.ajax({
url: "getData.action"
data: $('#actor_form').serialize(),
type: "GET",
dataType : "json",
success: function( json ) {
alert(json.name)
},
error: function( xhr, status, errorThrown )
{
alert( "Sorry, there was a
problem!" );
},
complete: function( xhr, status ) {
alert( "The request is
complete!" );
}
});
GET vs. POST
GET
only
"getting" data from the server, not changing data on the server.
POST
operations
where you are changing data on the server
Data Types
jQuery
generally requires some instruction as to the type of data you expect to get
back from an Ajax request
text :For
transporting simple strings.
html :For
transporting blocks of HTML to be placed on the page.
script :For adding a new script to the page.
json :For
transporting JSON-formatted data, which can include strings, arrays, and
objects.
jsonp :For transporting JSON data from another domain.
xml :For
transporting data in a custom XML schema.
Ajax
and Forms
--------------------------------------------
1. $("#form").serialize()
·
The .serialize() method serializes a form's
data into a query string.
·
For the element's value to be serialized, it
must have a name attribute.
·
Please note that values from inputs with a
type of checkbox or radio are included only if they are checked.
Example:
// Turning form data into a query string
$( "#myForm" ).serialize();
// Creates a query string like this:
// field_1=something&field2=somethingElse
2. $("#form").serializeArray()
Sometimes
your application would work better if you sent over an array of objects
// Creating an array of objects
containing form data
$( "#myForm"
).serializeArray();
// Creates a structure like this:
// [
//
{
//
name : "field_1",
//
value : "something"
//
},
//
{
//
name : "field_2",
//
value : "somethingElse"
//
}
// ]
Ajax
Events
--------------------------
//
Setting up a loading indicator using Ajax Events
$(
"#loading_indicator" )
.ajaxStart(function()
{
$( this ).show();
})
.ajaxStop(function() {
$( this ).hide();
});
Ajay
– in Java web Applications
Example-1
@RequestMapping("/addActor.sj")
@ResponseBody
public String addActor(@ModelAttribute("actorBo") ActorBo p){
System.out.println(" In
Controller start);
p.setActor_dob(DateUtil.mysqlDate(p.getActor_dob()));
int x = actorService.addActor(p);
ModelAndView view = new ModelAndView("temp");
view.addObject("msg", "Save
Operation");
view.addObject("status", x);
ObjectMapper
mapper = new ObjectMapper();
UtilBo utilBo = new UtilBo();
utilBo.setMsg("Hello");
utilBo.setStatus("231");
mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
String json_stu="";
try {
json_stu = mapper.writeValueAsString(utilBo);
System.out.println(json_stu);
} catch (Exception e) {
// TODO Auto-generated
catch block
e.printStackTrace();
}
return json_stu;
}
$('#actor_saveButton').click( function() {
alert('form Submits');
$.ajax({
url: 'addActor.sj',
type: 'post',
data: $('#actor_form').serialize(),
dataType:"json",
success: function(data) {
alert(''+data.msg);
toastr.warning("Data Is
saved");
},
error: function( xhr, status,
errorThrown ) {
alert( "Sorry, there was a
problem!" );
alert(xhr +" : "+status+" : "+errorThrown );
}
});
});
$('#section').on('change',function(){
$.getJSON('sectionBasedLessons.action',
{'sectionid':$(this).val()},
function(input){
$("#lessons option").remove();
$("#lessons").append(input.lessons);
$('#sub_lessons').select2({tags:[""],placeholder: "Select
sub-lessons"});
});
});
$.ajax({
type: 'POST',
url: 'delete_lesson.action',
data: 'lessonIds=' +
lessonIds_Array.toString(),
success: function (result) {
$('#table_data').html(result);
$('#lesson_name').val("");
//
toastr.success($('#successMsg').val());
//
toastr.success($('#errorMsg').val());
},
error: function (e) {
toastr.error("OOps!
Selected lessons not Deleted please Try again");
}
});
toastr.error("Select
Section", "Error Info");
toastr.success("SOk"," Ok ");
toastr.info("info"," Ok
");
toastr.warning("SOk","
Ok ");
===================================================
In PHP
====================================================
$("#regButton").click(function() {
var str = $("form").serialize();
var url = "get/registerAjax.php?"+str;
alert("Serialized : "+str+ " URL : "+url);
// do the extra stuff here
$.ajax({
type: "POST",
url: "get/registerAjax.php",
data: str,
success: function( data ) {
alert(data);
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
}
})
})
</script>