ios development - How to do JSON parser? - ios

I'm new to ios development. Now I get a JSON file from server.
I use NSDictionary to get objects. When I debug, I could get "name", "address" values.
But I don't know how can I get all "dish" elements from "recommendation" Object? In java development, I know recommendation is an object, and "dish" is an array element. But I don't know what happen in ios.
{
"results": [
{
"name": "ollise",
"address": "columbia university",
"geo": [
{
"coordinates": 40
},
{
"coordinates": 70
}
],
"logo": "http:\/\/a0.twimg.com\/profile_images\/3159758591\/1548f0b16181c0ea890c71b3a55653f7_normal.jpeg",
"recommendation": [
{
"dish": "dish1"
},
{
"dish": "dish2"
}
],
}
]
}
By the way, in JSON, I store URL of an image in "logo", but I cannot get the value when debugging. Should I use some special format?
[Restaurant setname:[Dict objectForKey:#"name"]] // I could get name
[Restaurant setlogo:[Dict objectForKey:#"logo"]] // I can get nothing!

This is the way to do it
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:yourData options:NSJSONReadingMutableLeaves error:nil];
NSDictionary *results = [[response objectForKey:#"results"] objectAtIndex:0];
NSString *name = [response objectForKey:#"name"];
//... get other objects
NSArray *recommendation = [results objectForKey:#"recommendation"];
NSDictionary *recommendation1 = [recommendation objectAtIndex:0];
NSDictionary *recommendation2 = [recommendation objectAtIndex:1];
NSString *dish = [recommendation1 objectForKey#"dish"];
NSString *dish1 = [recommendation2 objectForKey#"dish"];
[Restaurant setname:name];
NSString *logo = [results objectForKey:#"logo"];
[Restaurant setlogo:logo];
The results is the same dictionary as the one in the JSON. Treat anything with braces ({}) as an NSDictionary and brackets ([]) as an NSArray. dish is not an array element, it is a key in a dictionary that is an array element.

Related

Unable to convert to a proper format of NSString from NSArray in iOS

I want to send below JSON parameter in an API call, but the string of contacts array which is used below is confusing and I'm unable to form it in iOS. Below is the working JSON parameter tested in Rest client. How to form a similar pattern of string containing an array of contacts in iOS?
Working JSON Parameter,
{
"contacts": "[\"5555228243\",\"919677012480\"]",
"phno": "919791871448",
"device": "iphone",
"key": "key",
"name": "Logunath Subramaniyan",
"files": "files"
}
My code below for conversion,
NSMutableDictionary *reqData = [[NSMutableDictionary alloc]init];
[reqData setObject:[FMCoredDataUtility fetchDetailForKey:kmobileNumber] forKey:#"phno"];
[reqData setObject:[FMCoredDataUtility fetchUserNameForKey:kuserName ]forKey:#"name"];
[reqData setObject:#"iphone" forKey:#"device"];
[reqData setObject:#"key" forKey:#"key"];
[reqData setObject:[self getMobileContacts ] forKey:#"contacts"];
[reqData setObject:#"files" forKey:#"files"];
-(NSArray*)getMobileContacts{
contactNumbers = [addUtility getContactNumbers];
for ( int i = 0; i < [contactNumbers count]; i++) {
[filteredContacts addObject:[[[contactNumbers objectAtIndex:i] componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:#""]];
}
return filteredContacts;
}
Framed error JSON parameter,
{
"contacts": [
"5555228243",
"5554787672",
"4085555270",
"4085553514",
"5556106679",
"5557664823",
"7075551854",
"8885555512",
"8885551212",
"5555648583",
"4155553695",
"919677012480"
],
"phno": "919791871448",
"device": "iphone",
"key": "key",
"name": "Logunath Subramaniyan",
"files": "files"
}
and error I'm getting in console is,
value __NSCFConstantString *
#"JSON text did not start with array or object and option to allow fragments not set."
0x000000010cf2ed50
Here is a way in which you can convert your ios array to JSON string
NSArray *contactsArray = [self getMobileContacts ];//This will be your contacts array
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myArray options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[reqData setObject:jsonString forKey:#"contacts"];

Parsing JSON Object - Objective C

I'm struggling to see why this code is not working. I have many other views using different JSON services. All working normally. However, this one is simply not. I retrieve the values back from the service as I expect however when trying to loop over it (see below code) the Array is Nil. Clearly something simple I have missed but I have been looking at this issue far to long.
Abstract View of JSON service;
{
"0": {
"altitude": "14500",
"latitude": "41.41555",
"longitude": "-73.09605",
"realname": "David KGNV"
},
"1": {
"altitude": "61",
"latitude": "33.67506",
"longitude": "-117.86739",
"realname": "Mark CT"
},
"10": {
"altitude": "38161",
"latitude": "40.51570",
"longitude": "-93.25554",
"realname": "Bob CYYZ"
},
"100": {
"altitude": "33953",
"latitude": "52.35600",
"longitude": "5.30384",
"realname": "Jim LIRQ"
}
}
Abstract view of the JSON call;
*Note the NSArray *currentMapArray valueKeyPath is set to "" as I need all elements within the JSON result.
NSError *_errorJson = nil;
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
if (_errorJson != nil) {
NSLog(#"Error %#", [_errorJson localizedDescription]);
} else {
//Do something with returned array
dispatch_async(dispatch_get_main_queue(), ^{
NSDictionary *mapJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
//Loop through the JSON array
NSArray *currentMapArray = [mapJson valueForKeyPath:#""];
//set up array and json call
mapArray = [[NSMutableArray alloc]init];
for (int i = 0; i< currentMapArray.count; i++)
{
//create our object
NSString *nAltitude = [[currentMapArray objectAtIndex:i] objectForKey:#"altitude"];
NSString *nRealname = [[currentMapArray objectAtIndex:i] objectForKey:#"realname"];
NSString *nLatitude = [[currentMapArray objectAtIndex:i] objectForKey:#"latitude"];
NSString *nLongitude = [[currentMapArray objectAtIndex:i] objectForKey:#"longitude"];
[mapArray addObject:[[LiveVatsimMap alloc]initWithaltitude:nAltitude andrealname:nRealname andlatitude:nLatitude andlongitude:nLongitude]];
}
The results of currentMapArray is NIL resulting the NSString not being filled out appropriately.
for (int i = 0; i< currentMapArray.count; i++)
Of course when I hard code the value of JSON node i.e. 10 into the ValueKeyPath then it provides the correct data results and populates accordingly.
Any ideas? Be nice...I'm only new at this objective c stuff.
Your JSON doesn't have an array - it is a dictionary of dictionaries.
You can iterate over it using
NSArray *keys=[jsonArray allKeys];
for (NSString *key in keys) {
NSDictionary *elementDictionary=jsonArray[key];
NSString *nAltitude = elementDictionary[#"altitude"];
NSString *nRealname = elementDictionary[#"realname"];
NSString *nLatitude = elementDictionary[#"latitude"];
NSString *nLongitude = elementDictionary[#"longitude"];
[mapArray addObject:[[LiveVatsimMap alloc]initWithaltitude:nAltitude andrealname:nRealname andlatitude:nLatitude andlongitude:nLongitude]];
}

Store App names in NSArray from JSON DATA which Stored in NSDictionary

I have retrive following response form Server in JSON format which I have sucessfully store in NSDictionary.
{
"#companyName" = "MobileAPPSDeveloper";
"#generatedDate" = "8/6/13 2:41 AM";
"#version" = "1.0";
application = (
{
"#apiKey" = 234FXPQB36GHFF2334H;
"#createdDate" = "2013-03-01";
"#name" = FirstApp;
"#platform" = iPhone;
},
{
"#apiKey" = 3PF9WDY234546234M3Z;
"#createdDate" = "2013-02-01";
"#name" = SecondAPP;
"#platform" = iPhone;
},
{
"#apiKey" = NXGQXM2347Y23234Q4;
"#createdDate" = "2013-05-22";
"#name" = ThirdApp;
"#platform" = Android;
}
);
}
This is method I have used.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[self convertDataIntoDictionary:responseData];
}
-(void)convertDataIntoDictionary:(NSData*)data{
NSDictionary *dictionary;
if (data.length>0) {
NSError *parsingDataError;
dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&parsingDataError];
if (parsingDataError) {
// [ErrorAlert showError:parsingDataError];
NSString *recievedString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Data Conversion Error When Parsing: %#", recievedString);
}
}
NSLog(#"Data back from server\n %#",dictionary);
NSArray *applicationDetails = dictionary[#"application"];
}
I can not go further then this?
I would like to get All NAME of APPS in Array.
Any help would be appreciate.
The basics of parsing JSON is:
{ }- dis represents dictionary
( )- dis represents array
So in your JSON, there is a dictionary at the root and inside it has a key application which cbntains an Array.
NSArray *applicationArray = [dictionary objectForKey:#"application"];
NSMutableArray *mutableAppNamesArray = [[NSMutableArray alloc]init];
Inside this array there are three NSDictionary at every index:
for(NSDictionary *dict in applicationArray){
NSString *appName = [dict objectForKey:#"#name"];
NSLog(#"app name : %#", appName);
[mutableAppNamesArray addObject:appName];
}
NSArray * appNamesArray = [NSArray arrayWithArray:mutableAppNamesArray];
I think this is not a proper format for JSON. JSON objects usually contain ':' instead of '='
Example :-
{
products_id: "476",
products_model: "XOLO Play",
products_price: "15499.0000",
products_image: "xolo-play-play-t1000-.jpg",
products_date_available: null,
products_last_modified: "2013-08-04 06:04:11",
products_date_added: "2013-08-04 06:03:10",
manufacturers_id: "17",
products_status: "1",
products_rating: null,
category_id: "11"
},
{
products_id: "18",
products_model: "Nokia Lumia 820",
products_price: "8990.0000",
products_image: "samsung-galaxy-ace-duos-gsm-mobile-phone-large-1.jpg",
products_date_available: null,
products_last_modified: "2013-07-30 03:45:28",
products_date_added: "2013-01-23 00:52:00",
manufacturers_id: "2",
products_status: "1",
products_rating: "3",
category_id: "11"
},
But if you still need to parse it then you might try as below:
First get into the array
by NSDictionary *array = [allValues objectForKey:#"application"]; then each index to NSDictionary and then object for key. If its your server response than try to make it in the proper JSON format.

iOS JSon parsing, array in array

I have a simple json format with an array within an array, but I can't figure out how to get the inner array. How do I grab the "Commute" tag as an NSArray or a NSDictionary?
Here is my json:
{
"Language": "EN",
"Place": [
{
"City": "Stockholm",
"Name": "Slussen",
"Commute": [
"Subway",
"Bus"
]
},
{
"City": "Gothenburg",
"Name": "Central station",
"Commute": [
"Train",
"Bus"
]
}
]
}
Here is my code:
NSString *textPath = [[NSBundle mainBundle] pathForResource:#"Places" ofType:#"json"];
NSError *error;
NSString *content = [NSString stringWithContentsOfFile:textPath encoding:NSUTF8StringEncoding error:&error]; //error checking omitted
NSData *jsonData = [content dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:jsonData
options:kNilOptions
error:&error];
NSArray* AllPlaces = [json objectForKey:#"Place"];
for(int n = 0; n < [AllPlaces count]; n++)
{
PlaceItem* item = [[PlaceItem alloc]init];
NSDictionary* place = [AllPlaces objectAtIndex:n];
item.City = [place objectForKey:#"City"];
item.Name = [place objectForKey:#"Name"];
NSDictionary* commutes = [json objectForKey:#"Commute"];
[self.placeArray addObject:(item)];
}
Your code should be:
NSArray* commutes = [place objectForKey:#"Commute"];
Thwt would give back an array holding "Subway" and "Bus".
I think the problem is the access to json, it should be place instead:
NSArray* commutes = [place objectForKey:#"Commute"];
NSArray *commutes = [place objectForKey:#"Commute"];
This will give you an NSArray with "Subway" and "Bus".
You can considerably shrink you code using KVC Collection Operators:
NSArray *commutes = [json valueForKeyPath:#"Place.#distinctUnionOfArrays.Commute"];
If you want all repeated commutes use #unionOfArrays modifier.

How can I get the JSON array data from nsstring or byte in xcode 4.2?

I'm trying to get values from nsdata class and doesn't work.
here is my JSON data.
{
"count": 3,
"item": [{
"id": "1",
"latitude": "37.556811",
"longitude": "126.922015",
"imgUrl": "http://175.211.62.15/sample_res/1.jpg",
"found": false
}, {
"id": "3",
"latitude": "37.556203",
"longitude": "126.922629",
"imgUrl": "http://175.211.62.15/sample_res/3.jpg",
"found": false
}, {
"id": "2",
"latitude": "37.556985",
"longitude": "126.92286",
"imgUrl": "http://175.211.62.15/sample_res/2.jpg",
"found": false
}]
}
and here is my code
-(NSDictionary *)getDataFromItemList
{
NSData *dataBody = [[NSData alloc] initWithBytes:buffer length:sizeof(buffer)];
NSDictionary *iTem = [[NSDictionary alloc]init];
iTem = [NSJSONSerialization JSONObjectWithData:dataBody options:NSJSONReadingMutableContainers error:nil];
NSLog(#"id = %#",[iTem objectForKey:#"id"]);
//for Test
output = [[NSString alloc] initWithBytes:buffer length:rangeHeader.length encoding:NSUTF8StringEncoding];
NSLog(#"%#",output);
return iTem;
}
how can I access every value in the JSON? Please help me.
look like this ..
NSString *jsonString = #"your json";
NSData *JSONdata = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError = nil;
if (JSONdata != nil) {
//this you need to know json root is NSDictionary or NSArray , you smaple is NSDictionary
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONdata options:0 error:&jsonError];
if (jsonError == nil) {
//every need check value is null or not , json null like ( "count": null )
if (dic == (NSDictionary *)[NSNull null]) {
return nil;
}
//every property you must know , what type is
if ([dic objectForKey:#"count"] != [NSNull null]) {
[self setCount:[[dic objectForKey:#"count"] integerValue]];
}
if ([dic objectForKey:#"item"] != [NSNull null]) {
NSArray *itemArray = [dic objectForKey:#"item"]; // check null if need
for (NSDictionary *itemDic in itemArray){
NSString *_id = [dic objectForKey:#"id"]; // check null if need
NSNumber *found = (NSNumber *)[dic objectForKey:#"found"];
//.....
//.... just Dictionary get key value
}
}
}
}
I did it by using the framework : http://stig.github.com/json-framework/
It is very powerfull and can do incredible stuff !
Here how I use it to extract an item name from an HTTP request :
(where result is the JSO string)
NSString *result = request.responseString;
jsonArray = (NSArray*)[result JSONValue]; /* Convert the response into an array */
NSDictionary *jsonDict = [jsonArray objectAtIndex:0];
/* grabs information and display them in the labels*/
name = [jsonDict objectForKey:#"wine_name"];
Hope this will be helpfull
Looking at your JSON, you are not querying the right object in the object hierarchy. The top object, which you extract correctly, is an NSDictionary. To get at the items array, and the single items, you have to do this.
NSArray *items = [iTem objectForKey:#"item"];
NSArray *filteredArray = [items filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:#"id = %d", 2];
if (filteredArray.count) NSDictionary *item2 = [filteredArray objectAtIndex:0];
Try JSONKit for this. Is is extremely simple to use.
Note sure if this is still relevant, but in iOS 5, apple added reasonable support for JSON. Check out this blog for a small Tutorial
There is no need to import any JSON framework. (+1 if this answer is relevant)

Resources