how can i get JSONObject from request(HttpServletRequest) in servlet..
Very simple:
JSONObject o = new JSONObject(request.getParameter("WHATEVER"));
Edit: Since you use json-lib, it's
JSONObject o = (JSONObject) JSONSerializer.toJSON(request.getParameter("WHATEVER"));
for you.
i am sending json object through ajax as below (using jQuery)
var userstr = "{'firstName':'"+$("#firstName").val()+"',";
userstr+= "'lastName':'"+$("#lastName").val()+"',";
userstr+= "'age':'"+$("#age").val()+"'}";
alert(userstr);
var userjson = eval("(" + userstr + ")");
alert(userjson);
$.ajax(
{ type: "POST",
url: "user.register",
data: userstr,
success: function(msg){
//var user = msg.parseJSON();
}
}
); // ajax ends
this sends JSON object to servlet...thats fine...
but how can load that JSON object into my Java Object like JSONObject ??
i am doing as below and that also runs fine
String userstr = readJSONStringFromRequest(request);
JSONObject userjson = null;
try {
userjson = JSONObject.fromObject(userstr);
System.out.println(userjson);
} catch(ParseException pe) {}
String fName = userjson.getString("firstName");
System.out.println(fName);
private String readJSONStringFromRequest(HttpServletRequest request) throws IOException {
BufferedReader reader = request.getReader();
StringBuilder sb = new StringBuilder();
String line = reader.readLine();
while (line != null) {
sb.append(line + "\n");
line = reader.readLine();
}
reader.close();
String data = sb.toString();
return data;
}
but i want to know that if there is any short way to do that
I am using json-lib api from sourceforge.net
See JSONObject(java.lang.String). This will create a JSONObject object if you're passing in a String that is valid JSON. The constructor throws a JSONException so you will have to handle that. This is just as well if you are sending in invalid JSON.
It really depends on what you are doing. For the most part, JSONObject will use bean getters to create your JSON object (if you pass a bean to the constructor). Otherwise you can pass an object along with a String array of names. Here, JSONObject will use reflection to figure out the public members of the object. It will then use the names you provide as the keys to this object.
JSONObject will handle anything of type Map without a problem. But if your object is a List, you need to use JSONArray. Another problem is if your Map contains a List. Then, for some reason, JSONObject can't figure out that it is a List and will use the standard String representation of the List (not what you want). The only way to handle that is to iterate over the Map and built the JSONObject manually.
As far as your question goes, I'm assuming that you have a servlet which has an action that will return JSON. In that case, make a new JSONObject and use the PrintWriter to and jsonObject.toString() to output your JSON.
You're doing it a bit the hard way. There's certainly an easier way to do this. Just send as normal request parameters, not as JSON. You can use jQuery.serialize() to gather all form fields as parameters. Here's a kickoff example of how the JSP should look like:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('#form').submit(function() {
$form = $(this);
$.post($form.attr('action'), $form.serialize(), function(response) {
alert(response); // "OK"
});
return false;
});
});
</script>
</head>
<body>
<form id="form" action="register" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit">
</form>
</body>
</html>
And here is how the servlet which listens on an url-pattern of /register/* can look like:
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username + "," + password);
response.getWriter().write("OK"); // You can write JSON string here.
}
With the jQuery form plugin it'll be more transparent.
$(document).ready(function() {
$('#form').ajaxForm(function(response) {
alert(response); // "OK"
});
});
To respond back from servlet to jQuery, it's easier if you return real JSON data. For example:
Map<String, Object> data = new HashMap<String, Object>();
if (userDAO.exist(username)) {
data.put("success", false);
data.put("message", "Username in use, please choose another");
} else {
userDAO.create(username, password);
data.put("success", true);
data.put("message", "User successfully registered");
}
response.setContentType("application/json");
response.getWriter().write(new Gson().toJson(data)); // Gson = Google Gson.
and then in jQuery:
$(document).ready(function() {
$('#form').ajaxForm(function(data) {
$('#message').addClass(data.success ? 'success' : 'error').text(data.message).show();
});
});