JSON network request

I am doing a simple network request where I receive the results in XML format. Is there a way to receive the results in JSON format (or this is up to the server what format to respond )?

local function networkListener( event )     if ( event.isError ) then         print( "Network error!" )     else         print ( "RESPONSE: " .. event.response )     end     local saveData = event.response local path = system.pathForFile( "myfile.txt", system.DocumentsDirectory ) local file = io.open( path, "w" ) file:write( saveData ) io.close( file ) file = nil end network.request( "http://www.carsales.com.au/cars/results?area=Stock&vertical=car&sortBy=TopDeal&q=(((Make%3D%5BToyota%5D)%26(Model%3D%5BCamry%5D))%26(Service%3D%5BCarsales%5D)%26(Year%3drange%5b2015..2015%5d))&WT.z\_srchsrcx=makemodel/format=json", "GET", networkListener, params )

Here u go

display.setStatusBar( display.HiddenStatusBar ) local json = require ("json") temp\_json = { time = "", milliseconds\_since\_epoch = "", date = "", } function IsInString(theString, theText) print("IsInString()") if (tonumber(string.find(theString, theText)) == nil) then print(" String Not Found."); return false; else -- check the pos if the string to confirm (not nil is not enough) if (tonumber(string.find(theString, theText)) \> 1) then print(" String Found."); return true; else print(" String Not Found."); return false; end end end local function processDownloadedData( event ) print("processDownloadedData()") local retval local dataReceived = false if ( event.isError ) then --Hostname not found? else if (event.response == nil) then -- Error - Unknown Error elseif (event.response == "") then -- Error - Unknown Error elseif (IsInString(event.response, "time") == true) then dataReceived = true --Decode temp\_json = nil; temp\_json = json.decode(event.response); elseif (IsInString(event.response, "error") == true) then --unauthorized if (IsInString(event.response, "unauthorized") == true) then retval = native.showAlert( "Error", "Unnauthorized" , { "OK" }, onGenericAlertBox) end end if temp\_json == false then -- No Data. - Thre was no data returned. else -- now do something with the data print("--json-data----------------------------------------------------------------------------") print("time: " .. tostring(temp\_json.time)); print("offset: " .. tostring(temp\_json.milliseconds\_since\_epoch)); print("date: " .. tostring(temp\_json.date)); print("---------------------------------------------------------------------------------------") end end end -- prepare the network request function getJSONData(url, action, in\_json, callback) print("getJSONData()") local json = require ( "json" ) local headers = {} -- headers["Authorization"] = "Basic " .. mime.b64( "username:password" ) headers["Content-Type"] = "application/json" local params = {} params.headers = headers params.body = json.encode( in\_json ) network.request ( url, action, callback, params ) end -- Call the Data (background Call so it wont pause your app) getJSONData("http://date.jsontest.com", "GET", temp\_json, processDownloadedData)

Uncommon the Authorisation line to add username and password to the host headers.

Also add code to check the strong returned, you may get a valid son file but unexpected contents to check the contents.

Thanks mate. I tried this on other websites but it doesn’t seem to be working. My main question is do all websites allow requesting data in JSON format?

Thanks

Amir

All data coming from websites has to be send in the right format. You cant just add “format=json” to the sent URL and expect the server to reconfigure the data on the way out.

Check some of these links out to learn more about JSON.  JSON is my preferred data exchange format over say XML.

http://www.google.com.au/search?safe=active&q=json&oq=json&gs_l=serp.3…1320.1624.0.2008.4.4.0.0.0.0.0.0…0.0.msedr…0…1c.1.64.serp…4.0.0.tXR1A-zC2Qc

No worries mate. I get it now.

Here u go

display.setStatusBar( display.HiddenStatusBar ) local json = require ("json") temp\_json = { time = "", milliseconds\_since\_epoch = "", date = "", } function IsInString(theString, theText) print("IsInString()") if (tonumber(string.find(theString, theText)) == nil) then print(" String Not Found."); return false; else -- check the pos if the string to confirm (not nil is not enough) if (tonumber(string.find(theString, theText)) \> 1) then print(" String Found."); return true; else print(" String Not Found."); return false; end end end local function processDownloadedData( event ) print("processDownloadedData()") local retval local dataReceived = false if ( event.isError ) then --Hostname not found? else if (event.response == nil) then -- Error - Unknown Error elseif (event.response == "") then -- Error - Unknown Error elseif (IsInString(event.response, "time") == true) then dataReceived = true --Decode temp\_json = nil; temp\_json = json.decode(event.response); elseif (IsInString(event.response, "error") == true) then --unauthorized if (IsInString(event.response, "unauthorized") == true) then retval = native.showAlert( "Error", "Unnauthorized" , { "OK" }, onGenericAlertBox) end end if temp\_json == false then -- No Data. - Thre was no data returned. else -- now do something with the data print("--json-data----------------------------------------------------------------------------") print("time: " .. tostring(temp\_json.time)); print("offset: " .. tostring(temp\_json.milliseconds\_since\_epoch)); print("date: " .. tostring(temp\_json.date)); print("---------------------------------------------------------------------------------------") end end end -- prepare the network request function getJSONData(url, action, in\_json, callback) print("getJSONData()") local json = require ( "json" ) local headers = {} -- headers["Authorization"] = "Basic " .. mime.b64( "username:password" ) headers["Content-Type"] = "application/json" local params = {} params.headers = headers params.body = json.encode( in\_json ) network.request ( url, action, callback, params ) end -- Call the Data (background Call so it wont pause your app) getJSONData("http://date.jsontest.com", "GET", temp\_json, processDownloadedData)

Uncommon the Authorisation line to add username and password to the host headers.

Also add code to check the strong returned, you may get a valid son file but unexpected contents to check the contents.

Thanks mate. I tried this on other websites but it doesn’t seem to be working. My main question is do all websites allow requesting data in JSON format?

Thanks

Amir

All data coming from websites has to be send in the right format. You cant just add “format=json” to the sent URL and expect the server to reconfigure the data on the way out.

Check some of these links out to learn more about JSON.  JSON is my preferred data exchange format over say XML.

http://www.google.com.au/search?safe=active&q=json&oq=json&gs_l=serp.3…1320.1624.0.2008.4.4.0.0.0.0.0.0…0.0.msedr…0…1c.1.64.serp…4.0.0.tXR1A-zC2Qc

No worries mate. I get it now.