/** * Customer class having Customer Details */ public class Customer { String f_name=""; String l_name=""; String address=""; int age=0; //Constructors public Customer(String f_name, String l_name, String address, int age) { super(); this.f_name = f_name; this.l_name = l_name; this.address = address; this.age = age; } //Getters and Setters public String getF_name() { return f_name; } public void setF_name(String f_name) { this.f_name = f_name; } public String getL_name() { return l_name; } public void setL_name(String l_name) { this.l_name = l_name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.simple.JSONObject; /** * Servlet implementation class ConvertJAva2JSON */ public class ConvertJava2JSON extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ConvertJava2JSON() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { process(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { process(request, response); } private void process(HttpServletRequest request, HttpServletResponse response) { JSONObject cusObj = new JSONObject(); Customer cus=new Customer("Ramesh","Das","BBSR",19); cusObj=generateJSONObject(cus); if(cusObj!= null) sendJSONResponse(response,cusObj); else System.out.println("No Result"); } /** * This method writes json object to the response * @param response * @param cusObj */ private void sendJSONResponse(HttpServletResponse response, JSONObject cusObj) { try{ response.getWriter().print("CustomerDetails" +"("+cusObj+")"); } catch(Exception ex) { System.out.println(ex.getMessage()); } } /** * This method returns the json object * and provide the Customer Object to the method -'generateJSONComponent' and returns a JSONObject object to process method * @param Customer * @return JSONObject */ @SuppressWarnings("unchecked") private JSONObject generateJSONObject(Customer cus) { JSONObject cusObj=new JSONObject(); cusObj.put("First Name", cus.getF_name()); cusObj.put("Last Name", cus.getL_name()); cusObj.put("Address", cus.getAddress()); cusObj.put("Age", cus.getAge()); return cusObj; } }