使用Lua CJSON库进行encode与decode操作完成对Json数据转化


本篇介绍如何在lua中对数据进行json的encode与decode,这里Himi采用cjson进行。首先简单介绍下cjson:

Lua CJSON 是 Lua 语言提供高性能的 JSON 解析器和编码器,其性能比纯 Lua 库要高 10 到 20 倍。Lua CJSON 完全支持 UTF-8 ,无需依赖其他非 Lua/LuaJIT 的相关包。

文档链接:  http://www.kyne.com.au/~mark/software/lua-cjson-manual.html

下面我们来详细介绍如何搭建cjson在lua的使用环境:

第一步:下载cjson包  cjson.zip: 

cjson.zip:     http://vdisk.weibo.com/s/xQ-P6

 

 第二步:将下载的cjson.zip解压并加入我们的项目中,如下图:

QQ20130416-1

第三步:加载我们的cjson

打开项目的AppDelegate.cpp ,

 (1)首先导入       #include “lua_extensions.h”

(2)在此类的applicationDidFinishLaunching函数中,在CCLuaStack 实例获取到之后进行添加如下代码:

1
2
3
CCLuaStack *pStack = pEngine->getLuaStack();
     lua_State* L = pStack->getLuaState();
luaopen_lua_extensions(L);

如下图所示:

QQ20130416-2

OK,完成如上几步,我们就可以在lua中使用cjson啦! 下面介绍通过lua cjson对数据进行json的转换:

 对数据进行encode与decode操作:

3
4
5
6
7
8
9
10
11
12
13
14
15
- - 简单数据 -
local tab = {}
tab[ "Himi" ] = "himigame.com"
数据转json
local cjson require "cjson"
local jsonData cjson.encode(tab)
 
print (jsonData)
打印结果:  { : "himigame.com" }
 
json转数据
local data cjson.decode(jsonData)
 
(data.Himi)
打印结果:  himigame.com

稍微复杂一些的数据:

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
----带数组的复杂数据-----
local _jsonArray={}
_jsonArray[1]=8
_jsonArray[2]=9
_jsonArray[3]=11
_jsonArray[4]=14
_jsonArray[5]=25
 
local _arrayFlagKey={}
_arrayFlagKey[ "array" ]=_jsonArray
 
local tab = {}
tab[ "Himi" ]= "himigame.com"
"testArray" ]=_arrayFlagKey
"age" "23"
 
--数据转json
local cjson = require "cjson"
local jsonData = cjson.encode(tab)
 
print(jsonData)
-- 打印结果: { : "23" , :{ :[8,9,11,14,25]},monospace!important; font-size:1em!important; line-height:1.1em!important; color:blue!important; overflow:visible!important; bottom:auto!important; float:none!important; height:auto!important; left:auto!important; outline:0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; min-height:inherit!important">"himigame.com" }
 
--json转数据
local data = cjson.decode(jsonData)
local a = data.age
local b = data.testArray.array[2]
local c = data.Himi
 
print( "a:" ..a.. "  b:" ..b.. "  c:" ..c)
-- 打印结果: a:23  b:9  c:himigame.com

相关文章

1.github代码实践源代码是lua脚本语言,下载th之后运行thmai...
此文为搬运帖,原帖地址https://www.cnblogs.com/zwywilliam/...
Rime输入法通过定义lua文件,可以实现获取当前时间日期的功能...
localfunctiongenerate_action(params)localscale_action=cc...
2022年1月11日13:57:45 官方:https://opm.openresty.org/官...
在Lua中的table(表),就像c#中的HashMap(哈希表),key和...