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>-- io.open opens a file at path. returns nil if no file found<br />
local file = io.open( 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 />
end</p>
<p>return contents<br />
end</p>
<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 />
end</p>
<p>end<br />
end</p>
<p>

HTTP POST call

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( "http://www.yourserver.com/your_json_file.php", "POST", networkListener, params ) )<br />

HTTP GET call

<br />
local json_file_by_get = jsonFile( network.request( "http://www.yourserver.com/your_json_file.php?parameter1=value1&parameter2=value2&parameter3=value3", "GET", networkListener ) )<br />