13

How can I get a JSONObject from a HttpServletRequest in servlets?

3
  • 2
    Have you searched, read, tried anything?
    – BoltClock
    Aug 5, 2010 at 11:13
  • @Bozho has a good point. There are a number of JSON libraries for Java, and I expect many of them use that class name.
    – Stephen C
    Aug 5, 2010 at 12:50
  • when in doubt, assume it's the reference JSON library from json.org Aug 5, 2010 at 13:48

5 Answers 5

17

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.

2
  • 3
    JSONObject does not have any constructor with String argument which API you are using ?? Aug 5, 2010 at 15:36
  • I'm using the JSON library from json.org. Aug 6, 2010 at 11:23
2

It seems like you must be using the net.sf.json.JSONObject version of JSONObject (this is not the json.org version).

For the net.sf.json.JSONObject version simply use

JSONObject.fromObject(Object obj)

where obj is either

  • a valid JSON formatted string
  • a Bean POJO with getters and setters.
1

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.

0

GSON is a fairly good Java-based JSON library.

0
0

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();
            });        
        });
1
  • 1
    The question is not related to jQuery nor JavaScript at all, this answer is OT. Jun 18, 2015 at 20:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.