JohnIdol
JohnIdol

Reputation: 50097

How to read JSON string in servlet

This question seems to have the answer to what I am trying to do, but it does not seem to work for me. The servlet posts fine and in the watch window I can see my json object there for the _parameters member variable of the servlet HttpRequest, but I can't seem to get the parameter out.

Here is my code.

Javascript:

// build data from input fields
var jsondata = '{"author":"TEST", "title":"XYZ"}';

$.ajax({
    type : 'POST',
    dataType : 'json',
    data: jsondata,
    url : '/submitquote',
    timeout : 5000,
    success : function(data, textStatus) {
        // whatever
    },
    error : function(xhr, textStatus, errorThrown) {
        // whatever
    }
});

Servlet (I also tried with "author" and "title" but nothing comes back):

// get data
String postData =  req.getParameter("jsondata");

This is what I see using variable watch for _parameters on the request object:

{{"author":"TEST", "title":"XYZ"}=}

How the heck do I get that stuff out?

Any help appreciated!

Upvotes: 1

Views: 5498

Answers (1)

Michael Lorton
Michael Lorton

Reputation: 44376

First, the datatype argument specifies the type of the data coming out, not the data going in.

Second, the data argument should give a dictionary of parameters, and one of the parameters in this case is the already-stringified JSON object:

var jsondata = {"author":"TEST", "title":"XYZ"};

$.ajax({
    type : 'POST',
    dataType : 'json',
    data: { jsondata : JSON.stringify(jsondata)},
    url : '/submitquote',
    timeout : 5000,
    success : function(data, textStatus) {
        // whatever
    },
    error : function(xhr, textStatus, errorThrown) {
        // whatever
    }
});

Now, req.getParameter("jsondata") has the (still-JSON-stringified) data and you need to parse it yourself. JSON.org makes a very nice library you can use.

Two further notes:

  1. There are two "jsondata" here. First is the JavaScript variable, assigned in the first line and used inside the stringify call; second is the Ajax parameter name, specified right after data: { and used in the getParameter call.
  2. If you are really just passing "author" and "title", you can forget all about JSON and just use your original Javascript plus req.getParameter("author") and req.getParameter("title").

Upvotes: 4

Related Questions