parsing JSON values from JSON Array in iOS - 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);
}

Related

Parsing values from NSArray based on JSON format

I have a NSArray which is based on JSON format. I requested it from the web and saved it in the array. I am trying to use a dictionary to get the values of "categoryname" and "subscore" and store them in new arrays, but they remain empty. Do I have to convert the array back to NSData using JSON serialisation or is there a more direct way to achieve this?
NSArray detailedscore:
{
"articles": [
{
"abstract": "text",
"title": "title"
}
],
"subscore": 3,
"categoryname": "Reporting"
},
{
"articles": [
{
"abstract": "text2",
"title": "title"
}
],
"subscore": 1,
"categoryname": "Power"
}]
}
Code:
for(int i = 0; i < [self.detailedscore count]; i++)
{
NSMutableDictionary * dc = [self.detailedscore objectAtIndex:i];
NSString * score = [dc objectForKey:#"subscore"];
NSString * categoryname = [dc objectForKey:#"categoryname"];
[self.allscores addObject:subscore];
[self.allcategories addObject:categoryname];
for (NSString *yourVar in allcategories) {
NSLog (#"Your Array elements are = %#", yourVar);
}
{} ----> means dictionary, []---> array..... this is a rule I follow while assinging the return value from webservices as NSArray or NSDictionary....
Depending on your current JSON format, perhaps this might give you an idea
NSMutableArray *categoryArray = [NSMutableArray new];
for (NSDictionary *childDict in self.detailedscore)
{
[categoryArray addObject:[childDict objectForkey:#"categoryname"]];
}
If you have the array use below code
for(int i = 0; i < [self.detailedscore count]; i++)
{
NSMutableDictionary * dc = [self.detailedscore objectAtIndex:i];
NSString * score = [dc objectForKey:#"subscore"];
NSString * categoryname = [dc objectForKey:#"categoryname"];
[self.allscores score];
[self.allcategories addObject:categoryname];
for (NSString *yourVar in allcategories) {
NSLog (#"Your Array elements are = %#", yourVar);
}
The problem wasn't in the array or dictionary or the web request. I didn't allocated the NSMutableArrays so they were empty all the time. The code works fine for extracting values from the array in case anyone wants to use it.
Hope this helps.
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!connectionError) {
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&connectionError];
NSLog(#"Dict %#",dict);
BOOL isValid = [NSJSONSerialization isValidJSONObject:dict];
if (isValid) {
[target getJSONFromresponseDictionary:dict forConnection:strTag error:connectionError];
}
else{
NSString *strResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[target getStringFromresponseDictionary:strResponse forConnection:strTag error:error];
}

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

Map JSON to NSDictionary in Objective-C

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 ....

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.

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