Shrayas
Shrayas

Reputation: 6994

Problem consuming JSON object in a servlet

This is what i'm trying to do and its pretty simple but i'm getting stuck: I'm trying to send a JSON object formed in JSP to a server side servlet and parse it .

What i've done till now:

$.ajax({
            data: jsontosend,
            url: 'MYSERVLET?name=asdf',
            success: function(res){
                alert('posted');
            }
        })

Problem:

Parameter = name
Parameter = {"ticker":"asd","date":"asd","bucket":"300","entry":[{"type":"asd","indicator":"asd","condition":"asd"}],"exit":[{"type":"qwe","indicator":"qwe","condition":"qwe"}]}

Anyone have an idea as to what the problem is ?

Also i tried looking at this question here on stackoverflow but the same problem exists there too. Also there is a duplicate question which hasn't been answered .

Help! :(

Upvotes: 3

Views: 4847

Answers (2)

Esben Skov Pedersen
Esben Skov Pedersen

Reputation: 4517

You don't get the json object in your servlet. JQuery transforms it into http parameters like what you get from a form. Example: ?ticker=asd&bucket=300

So to answer your question. There is no single name. The json objected is exploded t multiple names.

EDIT: try adding type: 'post'

for your request. You can also add processData: false in which case JQuery will send json and not http params. Anyway I really recommend using a http debugger like fiddler which will make it apperant what is being sent back and forth.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691685

Read http://api.jquery.com/jQuery.ajax/#sending-data-to-server:

The data option can contain either a query string of the form key1=value1&key2=value2, or a map of the form {key1: 'value1', key2: 'value2'}. If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent.

So, you should use

$.ajax({
        data: {theNameOfTheParameter : jsontosend,
               name : 'asdf'},
        url: 'MYSERVLET',
        success: function(res){
            alert('posted');
        }
    })

and use request.getParameter("theNameOfTheParameter") to get the JSON string.

Upvotes: 5

Related Questions