使用Lua CJSON库进行encode与decode操作完成对Json数据转化
来源:互联网 发布:数据库设计原则和步骤 编辑:程序博客网 时间:2024/04/19 20:10
本篇介绍如何在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解压并加入我们的项目中,如下图:
第三步:加载我们的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);
如下图所示:
OK,完成如上几步,我们就可以在lua中使用cjson啦! 下面介绍通过lua cjson对数据进行json的转换:
对数据进行encode与decode操作:
1
2
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)
-
-
打印结果: {
"Himi"
:
"himigame.com"
}
-
-
json转数据
local data
=
cjson.decode(jsonData)
print
(data.Himi)
-
-
打印结果: himigame.com
稍微复杂一些的数据:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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"
tab[
"testArray"
]=_arrayFlagKey
tab[
"age"
]=
"23"
--数据转json
local cjson = require
"cjson"
local jsonData = cjson.encode(tab)
print(jsonData)
-- 打印结果: {
"age"
:
"23"
,
"testArray"
:{
"array"
:[8,9,11,14,25]},
"Himi"
:
"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
0 0
- 使用Lua CJSON库进行encode与decode操作完成对Json数据转化
- 使用Lua CJSON库进行encode与decode操作完成对Json数据转化
- 使用Lua CJSON库进行encode与decode操作完成对Json数据转化
- 使用Lua CJSON库进行encode与decode操作完成对Json数据转化
- 【COCOS2DX-LUA 脚本开发之十】使用Lua CJSON库进行encode与decode操作完成对Json数据转化
- 【COCOS2DX-LUA 脚本开发之十】使用Lua CJSON库进行encode与decode操作完成对Json数据转化
- 【COCOS2DX-LUA 脚本开发之十】使用Lua CJSON库进行encode与decode操作完成对Json数据转化
- 【COCOS2DX-LUA 脚本开发之十】使用Lua CJSON库进行encode与decode操作完成对Json数据转化
- lua教程十---使用Lua CJSON库进行encode与decode操作完成对Json数据转化
- 使用Lua CJSON库进行encode与decode操作
- Lua 使用cjson解析json数据(Mac环境)
- 使用CJSON库实现XML与JSON格式的相互转化
- lua-cjson安装与使用
- 使用cJSON库打包json数据及解析json数据
- lua中的json.decode和json.encode解析
- Lua:下载安装lua-cjson,lua操作json代码
- lua -- encode and decode
- Lua cjson库在windows下的编译与使用
- 驱动程序调试(一)————打印: prink, 自制proc文件
- 搭建 Jenkins 持续集成环境
- HDU 1151 Air Raid 最小路径覆盖,二分图匹配匈牙利算法(邻接表存关系)处理有向图
- 第一次图像取反
- UTF-8的bom问题
- 使用Lua CJSON库进行encode与decode操作完成对Json数据转化
- springboot 整合web项目支持jsp
- 一个手机图表(echarts)折线图的封装
- QRCode和zxing的实例
- cxf创建webService
- R语言 RStudio快捷键
- 欢迎使用CSDN-markdown编辑器
- Linux Kernel 学习笔记5:字符设备
- myeclipse8.5打包jar并引入第三方jar包