天天看點

quick-cocos2d-x解析json

先聲明下我采用的是http伺服器,用戶端用的curl。

下面是我伺服器端代碼,我用的是jetty,其他伺服器的都類似:

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);
	}	

}
           

熟悉json的同學可以看懂我傳回的json的資料。

下面是用戶端lua代碼:

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是上面servlet的響應url。

json.decode()函數會傳回一個已經解析好的table也就是上面的變量t。

然後就可以通過t來通路擷取到的資料了。