20

I am posting a jQuery AJAX POST to a servlet and the data is in the form of JSON String. Its getting posted successfully but on the Servlet side I need to read these key-val pairs into a Session Object and store them. I tried using JSONObject class but I am not able to get it.

Heres the code snippet

$(function(){
   $.ajax(
   {
      data: mydata,   //mydata={"name":"abc","age":"21"}
      method:POST,
      url: ../MyServlet,
      success: function(response){alert(response);
   }
});

On the Servlet side

public doPost(HTTPServletRequest req, HTTPServletResponse res)
{
     HTTPSession session = new Session(false);
     JSONObject jObj    = new JSONObject();
     JSONObject newObj = jObj.getJSONObject(request.getParameter("mydata"));
     Enumeration eNames = newObj.keys(); //gets all the keys

     while(eNames.hasNextElement())
     {
         // Here I need to retrieve the values of the JSON string
         // and add it to the session
     }
}
3
  • Why not create a javascript object mydata that contains mydata.name, mydata.age? Then you could just pull the specific parameters in your servlet instead of decoding json? Commented Mar 17, 2011 at 12:30
  • I cannot 'cos the key-vals can vary from one POST to another Commented Mar 17, 2011 at 12:37
  • You could, when in your function decode the json with JQuery, fwiw. Not saying that SHOULD be your solution, but it would accomplish the same thing. Commented Mar 17, 2011 at 12:46

4 Answers 4

18

if you use jQuery .ajax(), you need to read the HttpRequest input stream

    StringBuilder sb = new StringBuilder();
    BufferedReader br = request.getReader();
    String str;
    while( (str = br.readLine()) != null ){
        sb.append(str);
    }    
    JSONObject jObj = new JSONObject(sb.toString());
Sign up to request clarification or add additional context in comments.

Comments

15

You aren't actually parsing the json.

JSONObject jObj = new JSONObject(request.getParameter("mydata")); // this parses the json
Iterator it = jObj.keys(); //gets all the keys

while(it.hasNext())
{
    String key = it.next(); // get key
    Object o = jObj.get(key); // get value
    session.putValue(key, o); // store in session
}

1 Comment

First line inside while -- >Required type:StringProvided:Object
2

So here goes my example. I used json.JSONTokener to tokenize my String. ( Json-Java API from here https://github.com/douglascrockford/JSON-java )

String sJsonString = "{\"name\":\"abc\",\"age\":\"21\"}";
// Using JSONTokener to tokenize the String. This will create json Object or json Array 
// depending on the type cast.
json.JSONObject jsonObject = (json.JSONObject) new json.JSONTokener(sJsonString).nextValue();

Iterator iterKey = jsonObject.keys(); // create the iterator for the json object.
while(iterKey.hasNext()) {
    String jsonKey = (String)iterKey.next(); //retrieve every key ex: name, age
    String jsonValue = jsonObject.getString(jsonKey); //use key to retrieve value from 

    //This is a json object and will display the key value pair.

    System.out.println(jsonKey  + " --> " + jsonValue  );
}

Output:
age-->21
name-->abc

1 Comment

Any idea how to solve this java.lang.NoClassDefFoundError: org/json/JSONTokener
0

If you just want to marshal it into a Map then try Jackson.

ObjectMapper mapper = new ObjectMapper();
...
Map<String, Object> data = mapper.readValue(request.getParameter("mydata"), Map.class);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.