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來訪問獲取到的數據了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章