Corona中文站

强大、易学的跨平台(iOS/Android)开发框架。QQ群1:74390406(满) 群2:221929599

导航

在Corona中使用JSON进行数据存储和网络传输

之前有篇文章讲解了如何在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 string
local jsonFile = function( filename, base )
 
-- set default base dir if none specified
if not base then base = system.ResourceDirectory; end
 
-- create a file path for corona i/o
local path = system.pathForFile( filename, base )
 
-- will hold contents of file
local contents
 
-- io.open opens a file at path. returns nil if no file found
local file = io.open( path, "r" )
if file then
-- read all contents of file into a string
contents = file:read( "*a" )
io.close( file ) -- close the file after using it
end
 
return contents
end
 
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 )

 

<< 如何在Corona App中加入Admob/InMobi等广告【附代码】在Corona中使用自定义字体 >>

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

最近发表

Powered By Z-Blog 1.8 Walle Build 100427 Copyright 2011-2015 BuildApp.Net. All Rights Reserved.