JavaEE: Build JSON string response in servlet

import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class MyServlet extends HttpServlet{ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Build json response object JsonObject jsonResp = new JsonObject(); jsonResp.addProperty("firstname","John"); jsonResp.addProperty("lastname","doe"); jsonResp.addProperty("age",40); JsonArray colleagues=new JsonArray(); colleagues.add("Peter"); colleagues.add("Jessica"); jsonResp.add(colleagues); // Send json response resp.setContentType("application/json"); resp.setCharacterEncoding("UTF-8"); resp.getWriter().write(jsonResp.toString()); } }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.