Map JSON to NSDictionary in Objective-C - ios

I have the following JSON from a Web service:
[
"{
"count":2,
"offers":{
"0":{
"nodeID":"654321",
"publicationDate":"1396272408",
"title":"My first title",
"locations":"New York City"
},
"1":{
"nodeID":"123456",
"publicationDate":"1396272474",
"title":"My second title",
"locations":"San Diego"
}
},
"error":"null",
"result":"success"
}"
]
I need to map this JSON to a NSDictionary. How can I do that?
I already tried the following
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&localError];
but it only gives me a dictionary with one object in it. I need to access all the fields of the JSON such as "count", "offers" etc. How can I achieve this?

You JSON output is not a dictionary but an array.
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSarray *parsedObject = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&localError];
for(NSDictionary *dict in parsedObject) {
NSNumber *count = [dict objectForKey:#"count"];
}
But the offer node is just weird, this would be better as an array.

Get your data in this form ... Your json Give error of ".....
[
{
"count": 2,
"offers":
{
"0": {
"nodeID": "654321",
"publicationDate": "1396272408",
"title": "Myfirsttitle",
"locations": "NewYorkCity"
},
"1": {
"nodeID": "123456",
"publicationDate": "1396272474",
"title": "Mysecondtitle",
"locations": "SanDiego"
}
},
"error": "null",
"result": "success"
}
]
You get data In Array [ having Dictionary in dictionary ....

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"];

covert json into dictionary in ios

i am try to convert this json data into dictionary but I can't please help me.
{
"homeMobileCountryCode": 310,
"homeMobileNetworkCode": 260,
"radioType": "gsm",
"carrier": "T-Mobile",
"cellTowers": [
{
"cellId": 39627456,
"locationAreaCode": 40495,
"mobileCountryCode": 310,
"mobileNetworkCode": 260,
"age": 0,
"signalStrength": -95
}
],
"wifiAccessPoints": [
{
"macAddress": "01:23:45:67:89:AB",
"signalStrength": 8,
"age": 0,
"signalToNoiseRatio": -65,
"channel": 8
},
{
"macAddress": "01:23:45:67:89:AC",
"signalStrength": 4,
"age": 0
}
]
}
I know only to convert from Dictionary to JSON like this
NSMutableDictionary * location = [[NSMutableDictionary alloc]init];
[location setValue:mobileCountryCode forKey:#"mobileCountryCode"];
[location setValue:mobileNetworkCode forKey:#"mobileNetworkCode"];
[location setValue:cellId forKey:#"cellId"];
[location setValue:locationAreaCode forKey:#"locationAreaCode"];
NSData *data = [NSJSONSerialization dataWithJSONObject:requestbodyInputDict options:NSUTF8StringEncoding error:nil];
NSString* jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"jsonString.....%#",jsonString);
NSData *requestBody = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
so please help me how to revers this process how to handle this.
Just check this code. It will convert your json to NSdictionary
NSString *jsonString = #"{ \"homeMobileCountryCode\": 310, \"homeMobileNetworkCode\": 260, \"radioType\": \"gsm\", \"carrier\": \"T-Mobile\", \"cellTowers\": [ { \"cellId\": 39627456, \"locationAreaCode\": 40495, \"mobileCountryCode\": 310, \"mobileNetworkCode\": 260, \"age\": 0, \"signalStrength\": -95 } ], \"wifiAccessPoints\": [ { \"macAddress\": \"01:23:45:67:89:AB\", \"signalStrength\": 8, \"age\": 0, \"signalToNoiseRatio\": -65, \"channel\": 8 } ] }";
NSError *jsonError;
NSData *objectData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
Use String replace method to replace " with \" it will work
what you are doing is you are directly accessing the "mobileCountryCode", "mobileNetworkCode" and so on.. which are element of json array "cellTowers" so if you want those values you can first have an array of "cellTowers" and there you go...

json iOS parsing error

I am trying to parse the following json into my iOS code.
{
"test": [
{
"id": "21",
"lat": "53.343377977116916",
"long": "-6.2587738037109375",
"address": "R138, Dublin, Ireland",
"name": "td56",
"distance": "0.5246239738790947"
},
{
"id": "11",
"lat": "53.343377977116916",
"long": "-6.245641708374023",
"address": "68-130 Pearse Street, Dublin, Ireland",
"name": "test1",
"distance": "0.632357483022306"
}
]
}
I am able to view the full json in my logs with the following code:
NSURL *blogURL = [NSURL URLWithString:#"URLHERE"];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *test = [dataDictionary objectForKey:#"test"];
NSLog(#"%#",dataDictionary);
if I change data dictionary to test in the log, I can display after the test root in my json , but if I try setup arrays to view, let's say the ID, the entire app will crash.
Could someone direct me in the right way to, let's say, display all the names in the NSLog? Each method I've tried has resulted in the application crashing.
Test is an array:
NSArray *test = [dataDictionary objectForKey:#"test"];
NSLog(#"test =%#", test);
for(NSDictionary *coordinates in test){
NSLog(#"id = %#", coordinates[#"id"]);
NSLog(#"lat = %#", coordinates[#"lat"]);
NSLog(#"long = %#", coordinates[#"long"]);
}
NSArray *array = [dataDictionary valueForKey:#"test"];
for(int i = 0; i < array.count; i++){
NSLog(#"%#", [array[i] valueForKey:#"name"]);
}
like that u can get NSLog whatever key you want
for id
NSLog(#"%#", [array[i] valueForKey:#"id"]);
for lat
NSLog(#"%#", [array[i] valueForKey:#"lat"]);
and so on.....
Happy coding

parsing JSON values from JSON Array in iOS

i am getting the response from the server in JSON array form like below :
{
"status": "success",
"data": [
{
"auth_Secret_ticket_refresh": "NULL",
"userId": "10632",
"loginEmail": "Raushan#gmail.com",
"auth_authorizationCode": "4cb8c5e8a7f5",
"accountType": "flickr",
"auth_Token": "23104658-d2e65d5f94554652",
"userName": "betterlabpune",
"auth_subdomain": "NULL"
},
{
"auth_Secret_ticket_refresh": "NULL",
"userId": "19629",
"loginEmail": "Ipad#gmail.com",
"auth_authorizationCode": "8b909cb3e0e1",
"accountType": "flickr",
"auth_Token": "77645323118718-bac668bc2b95ad89",
"userName": "betterlabpune",
"auth_subdomain": "NULL"
}
]
}
I want to extract the value from JSON array for the 0 index, value for "userId" and "userName".
i had tried to extract values in many ways ,below is my code:
NSMutableData * _responseData = [[NSMutableData alloc]init];
[_responseData appendData:data];
NSJSONSerialization *dataAsString=(NSJSONSerialization*)[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
// dataJson=(NSDictionary*)[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"data in register reponse : %#",dataAsString);
NSJSONSerialization *json;
NSDictionary *dataJson;
NSError *error;
NSDictionary *JSONE = [NSJSONSerialization JSONObjectWithData:_responseData options:0 error:nil];
NSLog(#"JSONE : %#",JSONE);
json=[NSJSONSerialization JSONObjectWithData:_responseData
options:NSJSONReadingMutableLeaves
error:&error];
[self processData:dataJson];
dataJson=[[NSDictionary alloc]init];
dataJson=(NSDictionary *)json;
NSString * status=[dataJson objectForKey:#"status"];
NSString * message=[[dataJson objectForKey:#"data"]objectForKey:#"id"];
NSLog(#"status : %#",status);
NSLog(#"message: %#",message);
NSMutableArray *argsArray = [[NSMutableArray alloc] init];
argsArray= [dataJson valueForKeyPath:#"status"];
NSLog(#" client Id : %#", [argsArray objectAtIndex:0]);
bet every time i get null in my result.
Please help me out.
Thank you for your precious time.
try this...
if ([[dataJson valueForKey:#"status"]isEqualToString:#"success"])
{
NSMutableArray *tempArray=[NSMutableArray array];
for (NSDictionary *tempDic in [dataJson valueForKey:#"data"])
{
[tempArray addObject:[tempDic valueForKey:#"userId"]];
}
NSLog(#"%#",tempArray);
}

ios development - How to do JSON parser?

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.

Resources