Download and parse a JSON file
Hey!
I need to acces to a webservice; that returns me a JSON file…
The service is set on Force Download; so i think i must write in a file; then read it.
There is no result; so here's my code; if anyone can help me:
var xhr3 = Titanium.Network.createHTTPClient();
xhr3.onload = function()
{
var f=Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory,'temp.json');
f.write(this.responseData); // the response you get
var file=Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, "temp.json");
if(file.exists()){
Ti.API.info('in file ' + file.nativePath);
var fcontent = file.read();
Ti.API.info('contents = ' + JSON.parse(fcontent.text));
}
};
xhr3.onerror = function()
{
Ti.API.info('in utf-8 error for POST');
};
xhr3.open("POST","adress");
xhr3.setRequestHeader("User-Agent", "App 1.0 (iPod touch; iPhone OS 3.1.3; fr_FR)");
var now = new Date();
var date = now.getYear() + '-' + now.getMonth() + '-' + now.getDate();
xhr3.send({"key":"key"});
The request have been tested; so it works.
Here's the Dbug
[INFO] in file /Users/name/Library/Application Support/iPhone Simulator/4.1/Applications/8500FA8B-5325-4BBD-98D7-1DCA60C84A7B/Documents/temp.json
[INFO] contents = null
It would be great to read directly the JSON file
3 Answers
-
Thanks for the answer; but here's the result:
[WARN] Exception in event callback. {
expressionBeginOffset = 1602;
expressionCaretOffset = 1631;
expressionEndOffset = 1644;
line = 70;
message = "Result of expression 'JSON.parse(this.responseText)' [null] is not an object.";
name = TypeError;
sourceId = 237605056;
sourceURL = "file://localhost/Users/name/dir/dir/dir/Resources/accueil.js";
}And I have no control on the webservice…
Thanks for your help!
-
What happens when you just try to POST to your JSON document's URL? In your onload handler, you should be able to say
var jsonObject = JSON.parse(this.responseText)
. -
Update:
With
var jsonObject = (this.responseData); Ti.API.info(jsonObject);
I got
[INFO] [object TiBlob]
How can convert this to a string?