Composing a simple JSON response in Java

Posted in :

要在 java 裡輸出 json, .jar 檔可以在這邊下載:
https://github.com/stleary/JSON-java

精簡範例:

import org.json.JSONObject;
public class Test {
    public static void main(String args[]){
       JSONObject jo = new JSONObject("{ \"abc\" : \"def\" }");
       System.out.println(jo.toString());
    }
}

using JSON
serialization

  org.json.JSONObject obj = new org.json.JSONObject();
  obj.put("success", false);
  obj.put("message", "PEBKAC");
  obj.toString(); 

deserialization

org.json.JSONObject obj = new org.json.JSONObject(responseAsString);  
obj.optBoolean("success"); // false
obj.optString("message"); // PEBKAC

using google-gson

public class MyObject
{
   private String message;
   private boolean success;
   public MyObject(String message, boolean success)
   {
      this.message = message;
      this.success = success;
   }
}  

serialization

   MyObject obj = new MyObject("PEBKAC", false);  
   new com.google.gson.Gson().toJSON(obj);

deserialization

   MyObject obj = new com.google.gson.Gson().fromJSON(responseAsString, MyObject.class);
   obj.getMessage();
   obj.getSuccess();

3. Creating an Entity

Let’s create an Employee entity which will later be returned from the Servlet as JSON:

public class Employee {
    private int id;
    private String name;
    private String department;
    private long salary;
}

Entity to JSON

To send a JSON response from the Servlet we first need to convert the Employee object into its JSON representation.

There are many java libraries available to convert an object to there JSON representation and vice versa. Most prominent of them would be the Gson and Jackson libraries. To learn about the differences between GSON and Jackson, have a look at this article.

A quick sample for converting an object to JSON representation with Gson would be:

String employeeJsonString = new Gson().toJson(employee);

Response and Content Type

For HTTP Servlets, the correct procedure for populating the response:

  1. Retrieve an output stream from the response
  2. Fill in the response headers
  3. Write content to the output stream
  4. Commit the response

In a response, a Content-Type header tells the client what the content type of the returned content actually is.

For producing a JSON response the content type should be application/json:

PrintWriter out = response.getWriter();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(employeeJsonString);
out.flush();

Response headers must always be set before the response is committed. The web container will ignore any attempt to set or add headers after the response is committed.

Calling flush() on the PrintWriter commits the response.

Example Servlet

Now let’s see an example Servlet that returns a JSON response:

@WebServlet(name = "EmployeeServlet", urlPatterns = "/employeeServlet")
public class EmployeeServlet extends HttpServlet {

    private Gson gson = new Gson();

    @Override
    protected void doGet(
      HttpServletRequest request, 
      HttpServletResponse response) throws IOException {
        
        Employee employee = new Employee(1, "Karan", "IT", 5000);
        String employeeJsonString = this.gson.toJson(employee);

        PrintWriter out = response.getWriter();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        out.print(employeeJsonString);
        out.flush();   
    }
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *