Corona SDK: Get JSON data from the Internet

If you want to receive a parsed JSON string from the Internet in your Corona project do as in the following example:

Include JSON library

<br />
require "json"<br />

Create the functions

Then create the functions which get the JSON string from the Internet.

<br />
local jsonFile = function( filename, base )</p>
<p>-- set default base dir if none specified<br />
if not base then base = system.ResourceDirectory; end</p>
<p>-- create a file path for corona i/o<br />
local path = system.pathForFile( filename, base )</p>
<p>-- will hold contents of file<br />
local contents</p>
<p>-- opens a file at path. returns nil if no file found<br />
local file = path, "r" )<br />
if file then<br />
-- read all contents of file into a string<br />
contents = file:read( "*a" )<br />
io.close( file ) -- close the file after using it<br />
<p>return contents<br />
<p>local function networkListener( event )<br />
if ( event.isError ) then<br />
print( "Network error!")<br />
else<br />
print ( "RESPONSE: " .. event.response )<br />
local t = json.decode( event.response )</p>
<p>-- Go through the array in a loop<br />
for key in pairs(t) do<br />
-- Here you can do whatever you like with the values<br />
print(t[key]["returnvalue1"])<br />
print(t[key]["returnvalue2"])<br />
print(t[key]["returnvalue3"])<br />
<p>end<br />


With the following lines of code you can call the above created functions to get data from the Internet.

<br />
postData = "parameter1=value1&parameter2=value2&parameter3=value3"</p>
<p>local params = {}<br />
params.body = postData</p>
<p>local json_file_by_post = jsonFile( network.request( "", "POST", networkListener, params ) )<br />


<br />
local json_file_by_get = jsonFile( network.request( "", "GET", networkListener ) )<br />