How to Read JSON in Servlet - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

How to Read JSON in Servlet

Share This

Code for index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#id1").click(function() { $.ajax({ url : "./TestServ", type : "POST", data: { json: JSON.stringify({ exam : { "text" : "ABC", "msg" : "9551667858", "all" : [ { "name" : "one" }, { "name" : "two" } ], "obj" : { "firstname" : "John", "lastname" : "Doe" } } })}, dataType : "json", success : function(result) { alert(result); $("#id2").html(result); }, error : function(result) { $("#id2").html("Error Occured! Contact with Admin."); } }); }); }); </script> </head> <body> <button id="id1">Send back</button> <p id="id2"></p> </body> </html>

Code for TestServ.java

package com.t4b.test; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @WebServlet("/TestServ") public class TestServ extends HttpServlet { private static final long serialVersionUID = 1L; public TestServ() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); System.out.println("Hello world!"); String jsonString = request.getParameter("json"); try { JSONObject jsonObj = new JSONObject(jsonString); JSONObject examObj = jsonObj.getJSONObject("exam"); System.out.println(examObj.getString("text")); System.out.println(examObj.getString("msg")); JSONArray allArray = examObj.getJSONArray("all"); System.out.println(allArray); List<String> list = new ArrayList<String>(); for (int i = 0; i < allArray.length(); i++) { list.add(allArray.getJSONObject(i).getString("name")); System.out.println(" " + list.get(i)); } JSONObject objObj = examObj.getJSONObject("obj"); System.out.println(objObj); System.out.println(objObj.getString("firstname")); } catch (JSONException e) { e.printStackTrace(); } // System.out.println(jsonString); out.print(jsonString); } }

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.