首页 > 程序开发 > 移动开发 > 其他 >

quick-cocos2d-x解析json

2013-05-29

先声明下我采用的是http服务器,客户端用的curl。下面是我服务器端代码,我用的是jetty,其他服务器的都类似:[java] public class JsonServlet extends HttpServlet { private static final long se...

先声明下我采用的是http服务器,客户端用的curl。

下面是我服务器端代码,我用的是jetty,其他服务器的都类似:


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

}熟悉json的同学可以看懂我返回的json的数据。

下面是客户端lua代码:


[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, "https://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, "https://localhost:8080/json", "POST")
request:start()
其中https://........./json是上面servlet的响应url。

json.decode()函数会返回一个已经解析好的table也就是上面的变量t。

然后就可以通过t来访问获取到的数据了。

相关文章
最新文章
热点推荐