0

I am using Ajax and JSON to pass some array to my servlet. I am using Struts1.3 as my framework. I am receiving null as the parameter when i get the parameter in ActionServlet.

    $.ajax({
    url: "startTest.do?cmdField=ajax",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data:JSON.stringify(answerJson),
    contentType:"application/json"
    //complete:callback
}); 

my JSON object answerJson value :

 {"answer":[{"qId":"13","selAns":"A"},{"qId":"2","selAns":"A"},{"qId":"12","selAns":"A"},{"qId":"6","selAns":"A"}]}

In my servlet, if I use the below statement gives null.

System.out.println(request.getParameter("answer"));

I use tried to use GSON as

JsonAns ans = gson.fromJson(request.getParameter("answer"), JsonAns.class);

which in turn gave me error.

How can i get the parameter values into List using GSON?

opalenzuela
  • 3,139
  • 21
  • 41
Arun
  • 3,701
  • 5
  • 32
  • 43

2 Answers2

1

I found the solution. The req.getParameter("anything") assumes a content type of "application/x-www-form-urlencoded" or a normal HTTP GET (for URL parameters).

When the content type is "application/json", we need to use:

 Foo foo = gson.fromJson(req.getReader(), Foo.class);
Arun
  • 3,701
  • 5
  • 32
  • 43
0

I think you should get the json parameter first like this

send the param like

answer=json 

when sending request

then get json using this

String jsonStr=request.getParameter("answer");

then convert json string to json obj then use gson to parse

Hope I helped.

Chakradhar Vyza
  • 285
  • 4
  • 11
  • I need to send it as a post parameter. Thats the problem. – Arun Oct 07 '13 at 11:00
  • There are two ways you can simply change content type to html/text and send data as answer=json or read [this](http://stackoverflow.com/questions/17802851/reading-json-values-in-servlet) to get a better idea on how to send and retrieve json through ajax post request – Chakradhar Vyza Oct 07 '13 at 11:19
  • Ya but my requirement was to send it as a post parameter! – Arun Oct 08 '13 at 06:19