Shomit Shomit - 9 months ago 40
Java Question

Java serverlet parse Jason data

I want to post Jason 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

Jason is Successfully received.
Problem is there is no constructor for :

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

and i want to read both values and keys passed via java script....
PLease help


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.