Download JSON data via NSJSONSerialization - iphone

I have a JSON string from PHP's json_encode(). This is how it looks in JSONViewer.stack.hu, and this is how it looks in the browser.
Is it possible to use NSJSONSerialization to download the JSON data directly? If so, I am going to save the downloaded JSON data to SQLite by using FMDB.

id jsonObjectFromUrlString(NSString *urlString)
{
NSURL *url = [NSURL URLWithString:urlString];
NSError *error = nil;
id jsonObject = nil;
NSData *data = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
if(error)
NSLog(#"%#", error);
else
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if(error)
NSLog(#"%#", error);
return jsonObject;
}

JSON Serialization method. please refer this.
JSON Serialization
for database did you look at coredata.
please have a look at these ones.
add core data to existing xcode project.
A simple intro to use coreData

Related

How to parse json data with "var abcd =" header

I'm having problem with parsing json data file on iOS.
This is a sample from the data.json file:
var devs = [
{
"ident":"1",
"firstname":"Jan",
"lastname":"Kowalski",
"img":"http://www.placekitten.com/125/125",
"tech":"iOS, HTML5, CSS, RWD",
"github":"placeholder",
"opensource":"1",
"twitter":"placeholder"
},
{
"ident":"2",
"firstname":"WacĹaw",
"lastname":"GÄsior",
"img":"http://www.placekitten.com/124/125",
"tech":"Android, Java, Node.js",
"github":"GÄsiorBKR",
"twitter":"wacek5565"
},
and so on.
With "normal" json files I use:
NSURLResponse *response;
NSError *myError;
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://somerailsapplication/posts.json"] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0f];
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&myError];
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];
Unfortunately this solution doesn't work in this case.
Is there any chance to get this working without searching for specific string "var dev=[" and the last "]" in the downloaded data?
The response is javascript, not JSON, so you won't be able to use a JSON parser directly. If you can't change the server output, the easiest thing would be to strip the beginning and end of the data, as you suggested. You could also embed the response in an HTML template and evaluate it in a webview, but that seems like a lot of more work.
Starting at the point where you've got the data:
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&myError];
NSMutableString *dataAsString = [[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[dataAsString deleteCharactersInRange:NSMakeRange(0, 11)];
data = [dataAsString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];
This turns the data into a string, removes the first 11 characters, turns it back into data, and then parses it as normal. (I've changed it to NSArray since your data is in an array)

JSON returning null

I'm having a bit of trouble parsing some returned JSON. I'm fairly new to working with JSON. I'm trying to get the company name from the first JSON array element. I have a feeling that I'm confusing the use of NSMutabeArray and NSMutableDictionary. What I get is null. Any idea what I'm doing wrong?
NSString *url = #"http://www.google.com/finance/info?infotype=infoquoteall&q=C,JPM,AIG,AAPL";
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: url]];
//parse out the json data
NSError* error;
NSMutableArray* json = [NSJSONSerialization
JSONObjectWithData:data //1
options:kNilOptions
error:&error];
NSString* companyName = [[json objectAtIndex:0] objectForKey:#"name"] ; //Where I need some help
NSLog(#"we got %#", companyName);
Load that url in your browser. Looks like google is prefixing the JSON with //. I think NSJSONSerialization is tripping on that. Try this
NSRange range = NSMakeRange(2, [data length] - 3);
NSData *noPrefix = [data subdataWithRange:range];
Then send that to the parser.
You put in an error object, but you never looked at it. If you had, you would see that the data is corrupted:
Error Domain = NSCocoaErrorDomain Code = 3840 "The data couldn’t be read because it has been corrupted." (Invalid value around character 1.) UserInfo = 0x10030a8f0 { NSDebugDescription = Invalid value around character 1. }
I changed the value of the options parameter to see this error. I have
NSMutableArray* json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers |NSJSONReadingAllowFragments error:&error];

Parse json in objective-c for my iphone app

i have a problem parsing my json data for my iPhone app, I am new to objective-C. I need to parse the json and get the values to proceed. Please help. This is my JSON data:
[{"projId":"5","projName":"AdtvWorld","projImg":"AdtvWorld.png","newFeedCount":"0"},{"projId":"1","projName":"Colabus","projImg":"Colabus.png","newFeedCount":"0"},{"projId":"38","projName":"Colabus Android","projImg":"ColabusIcon.jpg","newFeedCount":"0"},{"projId":"25","projName":"Colabus Internal Development","projImg":"icon.png","newFeedCount":"0"},{"projId":"26","projName":"Email Reply Test","projImg":"","newFeedCount":"0"},{"projId":"7","projName":"PLUS","projImg":"7plusSW.png","newFeedCount":"0"},{"projId":"8","projName":"Stridus Gmail Project","projImg":"scr4.png","newFeedCount":"0"}]
On iOS 5 or later you can use NSJSONSerialization. If you have your JSON data in a string you can do:
NSError *e = nil;
NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
Edit To get a specific value:
NSDictionary *firstObject = [jsonArray objectAtIndex:0];
NSString *projectName = [firstObject objectForKey:#"projName"];
I would recommend using JSONKit library for parsing.
Here's a tutorial on how to use it.
You will basically end up with a dictionary and use objectForKey with your key to retrive the values.
JSONKit
or
NSJSONSerialization(iOS 5.0 or later)
I have had success using SBJson for reading and writing json.
Take a look at the documentation here and get an idea of how to use it.
Essentially, for parsing, you just give the string to the SBJsonParser and it returns a dictionary with an objectForKey function. For example, your code might look something like:
NSDictionary* parsed = [[[SBJsonParser alloc] init] objectWithString: json];
NSString* projId = [parsed objectForKey:#"projId"];
Use SBJson
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableDictionary *dicRes = [parser objectWithString:stringFromServer error:nil];
No need to use third party classes. Objective-c already includes handling JSON.
The class NSJSONSerialization expects an NSData object or reads from a URL. The following was tested with your JSON string:
NSString *json; // contains your example with escaped quotes
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingAllowFragments error:&error]
For more options with NSJSONSerialization see the documentation.

Fetch XML of Distance Matrix API (google) on iPhone

I'm trying to fetch the XML data from a query to the api without success...
I'm doing this:
[...]
NSURL *googleAPIurl = [NSURL URLWithString:#"http://maps.googleapis.com/maps/api/distancematrix/xml?origins=28.124822,-15.430006&destinations=28.126953,-15.429874|28.072056,-15.416574|28.103186,-15.417665|28.127916,-15.625403|28.099125,-15.418365|28.107740,-15.454050|28.050825,-15.454066|28.051640,-15.454104|28.101788,-15.423592|28.113750,-15.446980|28.098871,-15.420730|28.098217,-15.449371|28.083364,-15.418172&mode=driving&sensor=false"];
NSData *xmlData = [NSData dataWithContentsOfURL:googleAPIurl];
NSError *error;
GDataXMLDocument *xmlDocument = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error];
if (xmlDocument == nil)
{
NSLog(#"NIL XML");
}
[...]
I'm ALWAYS getting a nil XML. NSData is always nil. I don't know what is happening with this. If I use a url with one destination only it works, but not for more than one. Also, I'm using the same method to retrieve xml with google places api with no problems. This is driving me crazy...
Please point me in the right direction.
Thanks in advance.
I suggested replacing all of the '|' with '%7C'
Turns out this is the more proper method to cover all of these character encoding issues:
NSURL *googleAPIurl = [NSURL URLWithString:[distancesURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

Getting an XML file from URL to NSData object?

I need to load a .xml file from a URL adress into an NSData object for further parsing with some libraries that I already own, ( but they ask me the .xml file as NSData ), how could I do this ?
The url format would be something like this:
http://127.0.0.1/config.xml
Assuming it's UTF-8 data. If it's local (i.e. inside the bundle) something like:
NSError *error;
NSString* contents = [NSString stringWithContentsOfFile:PATHTOLOCALFILE
encoding:NSUTF8StringEncoding
error:&error];
NSData* xmlData = [contents dataUsingEncoding:NSUTF8StringEncoding];
If it's on a remote site, something like this should do it. Note that it's synchronous. If you need asynchronous loading, then you'll have to make your own networking or use something like ASIHTTPConnection to download the file first.
NSError *error;
NSString* contents = [NSString stringWithContentsOfUrl:[NSURL URLWithString:URLOFXMLFILE]
encoding:NSUTF8StringEncoding
error:&error];
NSData* xmlData = [contents dataUsingEncoding:NSUTF8StringEncoding];
You can call NSData's - (id)initWithContentsOfURL:(NSURL *)aURL routine. More info here:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html