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

使用Lua CJSON库进行encode与decode *** 作完成对Json数据转化,第1张

概述本篇介绍如何在lua中对数据进行json的encode与decode,这里Himi采用cjson进行。首先简单介绍下cjson: Lua CJSON 是 Lua 语言提供高性能的 JSON 解析器和编码器,其性能比纯 Lua 库要高 10 到 20 倍。Lua CJSON 完全支持 UTF-8 ,无需依赖其他非 Lua/LuaJIT 的相关包。 文档链接:  http://www.kyne.com
本篇介绍如何在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 *** 作:

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
总结

以上是内存溢出为你收集整理的使用Lua CJSON库进行encode与decode *** 作完成对Json数据转化全部内容,希望文章能够帮你解决使用Lua CJSON库进行encode与decode *** 作完成对Json数据转化所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1254154.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存