Pages

Wednesday, 29 April 2015

Gson with Ajax calls



Convert Class obj to JSON format:
Gson gson = new Gson();
strServiceResp = gson.toJson(classObj);
                                                                          
Convert JSON String to Class Object:
               Gson gson = new Gson();
ClassName classObj = (ClassName) gson.fromJson(jsonString, ClassName.class);

ClassVO.java
ClassVO{
 public String firstUser;
 public String lastUser;
}
Ajax:
var ClassVO = {
                "firstUser" : 'wilbert',
                "latsUser" : 'singh'
  };
 
   $.ajax({
         url:"webservice url",
                                type : "POST",
                                dataType : "json",
                                cache:false,
                                data :{jsonStr:JSON.stringify(ClassVO)},
                                               success: function(result){
                                              
                                               }
                                });

Data Representation:
data:{
                              Id : 101,
                              Name:'wilbert',
                              flag:'N'
                              },
                                                                                                                       
               @POST
               @Path("testName")
               @Produces("application/json")
               ClassVO methodName(String jsonStr);
              
              
              
              
                                                                                                                       
data : {
               'jsonStr' : JSON.stringify(javascript array name)
},
                                                                          
                                                                          
               @POST
    @Path("webservice name")
               @Consumes("application/json")
               @Produces("application/json")
               ClassVO methodName(String jsonStr);
              
              
              
               $.ajax( {
                                                                          
                              url: "wsurl",
                              type : 'POST',
                              dataType : "json",
                              contentType:"application/x-www-form-urlencoded; charset=UTF-8",
                              cache:false,
                              data:{jsonStr:JSON.stringify({"test":javascriptname})},
                              success: function(response) {
                                            
                              },
 });