之前有篇文章讲解了如何在corona中读写xml,xml虽然很强大,但是也存在一些问题,比如大量重复的标签使得文件变的很大,不利于网络传输,还有就是读取xml文件非常简单,但是在corona里面把内存数据序列化成xml文件,还是破费周折的。
Corona API里面提供了JSON模块,你不需要下载第三方的模块了,呵呵,而且接口非常简单,就三个:
json.decode()
json.encode()
json.null()
实际上,在大多数项目中,我们经常会用JSON来进行网络数据传输。
下面我来介绍一下如何在corona中使用JSON模块。
第一步,创建sample.json文件
{
"name": "Jack (\"Bee\") Nimble",
"format": {
"shape": "rect",
"width": 1920,
"height": 1080,
"interlace": false,
"framerate": 24
}
}
注:正如你可以从上面的示例中看到的,JSON和一个Lua表之间的主要区别是使用冒号“:”而不是等号“=”赋值。
如果你的JSON文件与sample.json一样进行以.json文件进行存储,那么你将首先把文件读取到一个变量中。这里有一个函数会帮你载入一个外部的JSON文件并将其存储在一个字符串变量中:
-- jsonFile() loads json file & returns contents as a stringlocal jsonFile = function( filename, base ) -- set default base dir if none specifiedif not base then base = system.ResourceDirectory; end -- create a file path for corona i/olocal path = system.pathForFile( filename, base ) -- will hold contents of filelocal contents -- io.open opens a file at path. returns nil if no file foundlocal file = io.open( path, "r" )if file then-- read all contents of file into a stringcontents = file:read( "*a" )io.close( file ) -- close the file after using itend return contentsend Decoding the JSON
require "json" local t = json.decode( jsonFile( "sample.json" ) )
t是如下结果: {name = "Jack (\"Bee\") Nimble",format = {shape = "rect",width = 1920,height = 1080,interlace = false,framerate = 24}}现在你可以像访问table一样去访问json数据了,是不是很爽,哈哈!!
Encoding an Existing Table
把table序列化成json字符串并保存。
非常简单,就是这样:local jsonString = json.encode( myLuaTable )