Thursday, May 16, 2019

Set JSON response to servlet



<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>${javax.servlet.version}</version>
</dependency>
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>${gson.version}</version>
</dependency>


=======================================================
public class Employee {
     
    private int id;
     
    private String name;
     
    private String department;
    
    private long salary;
 
    // constructors
    // standard getters and setters.
}

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


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


============================================================


If you use Jackson , then code will be as follows

private void writeResponse(HttpServletResponse aResponse, String errorCode, String errorMessage) {
  try {
   aResponse.setHeader("SAP-Exception", errorMessage);
   aResponse.setHeader("SAP-NFA-Exception-Code", errorCode);
   aResponse.setHeader("Content-Type", "application/json");
   ObjectMapper objectMapper = new ObjectMapper();
   NFAErrorResponse errorResponse = new NFAErrorResponse();
   errorResponse.setCode(errorCode);
   errorResponse.setMessage(errorMessage);
   String errorJsonString =objectMapper.writeValueAsString(errorResponse);
   PrintWriter out = aResponse.getWriter();
   out.print(errorJsonString);
   out.flush();
  } catch (IOException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
 }


for further info
https://www.baeldung.com/servlet-json-response






No comments:

Post a Comment