Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read json sent by ajax in servlet

I'm new to java and I struggling with this problem for 2 days and finally decided to ask here.

I am trying to read data sent by jQuery so i can use it in my servlet

jQuery

var test = [     {pv: 1000, bv: 2000, mp: 3000, cp: 5000},     {pv: 2500, bv: 3500, mp: 2000, cp: 4444} ];  $.ajax({     type: 'post',     url: 'masterpaket',     dataType: 'JSON',     data: 'loadProds=1&'+test, //NB: request.getParameter("loadProds") only return 1, i need to read value of var test     success: function(data) {      },     error: function(data) {         alert('fail');     } }); 

Servlet

protected void doPost(HttpServletRequest request, HttpServletResponse response)         throws ServletException, IOException {    if (request.getParameter("loadProds") != null) {       //how do i can get the value of pv, bv, mp ,cp    } } 

I really appreciate any help you can provide.

like image 389
Yosua Sofyan Avatar asked Oct 24 '13 14:10

Yosua Sofyan


People also ask

How to get JSON data from ajax in Java?

jQuery getJSON() Method The getJSON() method is used to get JSON data using an AJAX HTTP GET request.

How can we get JSON data from servlet to JSP using Ajax?

setContentType("application/json"); response. setCharacterEncoding("UTF-8"); PrintWriter out = response. getWriter(); String jsondata = new Gson(). toJson(cntrs); // out.

What is AJAX in JSON?

Advertisements. AJAX is Asynchronous JavaScript and XML, which is used on the client side as a group of interrelated web development techniques, in order to create asynchronous web applications.


2 Answers

You won't be able to parse it on the server unless you send it properly:

$.ajax({     type: 'get', // it's easier to read GET request parameters     url: 'masterpaket',     dataType: 'JSON',     data: {        loadProds: 1,       test: JSON.stringify(test) // look here!     },     success: function(data) {      },     error: function(data) {         alert('fail');     } }); 

You must use JSON.stringify to send your JavaScript object as JSON string.

And then on the server:

String json = request.getParameter("test"); 

You can parse the json string by hand, or using any library (I would recommend gson).

like image 88
siledh Avatar answered Sep 22 '22 13:09

siledh


You will have to use the JSON parser to parse the data into the Servlet

import org.json.simple.JSONObject;   // this parses the json JSONObject jObj = new JSONObject(request.getParameter("loadProds"));  Iterator it = jObj.keys(); //gets all the keys  while(it.hasNext()) {     String key = it.next(); // get key     Object o = jObj.get(key); // get value     System.out.println(key + " : " +  o); // print the key and value } 

You will need a json library (e.g Jackson) to parse the json

like image 29
Rakesh Soni Avatar answered Sep 21 '22 13:09

Rakesh Soni