First declare that I use the http server and the curl used by the client.
Below is my server code, I use jetty, and other servers are similar:
[Java] public class JsonServlet extends HttpServlet {
Private static final long serialVersionUID = 1L;
@ Override
Protected void doPost (HttpServletRequest req, HttpServletResponse resp)
Throws ServletException, IOException {
Resp. setContentType ("application/json ");
Resp. setCharacterEncoding ("UTF-8 ");
Map map = new HashMap ();
Map. put ("name", "json ");
Map. put ("bool", Boolean. TRUE );
Map. put ("int", new Integer (1 ));
Map. put ("arr", new String [] {"a", "B "});
String jsonStr = JSONArray. fromObject (map). toString ();
Resp. getWriter (). println (jsonStr );
Resp. flushBuffer ();
System. out. println (jsonStr );
}
}
Public class JsonServlet extends HttpServlet {
Private static final long serialVersionUID = 1L;
@ Override
Protected void doPost (HttpServletRequest req, HttpServletResponse resp)
Throws ServletException, IOException {
Resp. setContentType ("application/json ");
Resp. setCharacterEncoding ("UTF-8 ");
Map map = new HashMap ();
Map. put ("name", "json ");
Map. put ("bool", Boolean. TRUE );
Map. put ("int", new Integer (1 ));
Map. put ("arr", new String [] {"a", "B "});
String jsonStr = JSONArray. fromObject (map). toString ();
Resp. getWriter (). println (jsonStr );
Resp. flushBuffer ();
System. out. println (jsonStr );
}
} Anyone familiar with json can understand the json data returned by me.
The following is the client lua code:
[Html] local function callback (event)
Local OK = (event. name = "completed ")
Local request = event. request
Local response = request: getResponseString ()
Print (response)
Local json = require ("framework. shared. json ")
Local t = json. decode (response)
Print (t)
End
Local request = network. createHTTPRequest (callback, "http: // localhost: 8080/json", "POST ")
Request: start ()
Local function callback (event)
Local OK = (event. name = "completed ")
Local request = event. request
Local response = request: getResponseString ()
Print (response)
Local json = require ("framework. shared. json ")
Local t = json. decode (response)
Print (t)
End
Local request = network. createHTTPRequest (callback, "http: // localhost: 8080/json", "POST ")
Request: start ()
Http: // ....../json is the response url of the servlet above.
The json. decode () function returns a parsed table, that is, the preceding variable t.
Then you can access the obtained data through t.