Shomit Shomit - 1 year ago 99
Java Question

Java serverlet parse JSON data

I want to post JSON object from JavaScript to java serverlet.
I used the following javaScript code :

var a = {};
function SaveInfo(c)
document.getElementById("saveButton").className = "savebutton";
document.getElementById("cancelButton").className = "cancebutton";
var z= $(c).parent().parent().attr('id');
a[z] = c.value;

if( document.getElementById("saveButton").className=="savebutton")
url: "../../update",
type: 'POST',
dataType: 'json',
data: JSON.stringify(a),
contentType: 'application/json',
mimeType: 'application/json',
success: function (data) {
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);

and following java code :

public void doPost(HttpServletRequest req, HttpServletResponse res){
JSONObject jObj;
jObj = new JSONObject(req.getParameter("mydata")); // this parses the json
Iterator it = jObj.keys();

String key = (String); // get key
Object o = jObj.get(key); // get value
// store in session

JSON is successfully received.
Problem is there is no constructor for :

jObj = new JSONObject(req.getParameter("mydata"));

I want to read both values and keys passed via javascript.

Answer Source

For your purpose you can simply use a form, simply parse it like:

    Map<String, String[]> map = request.getParameterMap();

    for(Entry<String, String[]> e : map.entrySet()){
        response.getWriter().write(e.getKey() + ":" + e.getValue()[0] + "\n");

Use json when you want to send an object or a complex data array etc.

Hope that completes your work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download