Converting JSON Data from NSData to NSDictionary - iphone

I have a PHP service that returns me the following response in NSData format. After converting the same into NSString using:
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
I get the following:
[
{
"Emp_Name": "Krishna Mamidi",
"Emp_Designation": "Driver",
"Emp_Type": "Permanent",
"Joining_Date": "05-MAR-2011",
"Salary": 10000
},
{
"Emp_Name": "Aditya Reddy",
"Emp_Designation": "supervisor",
"Emp_Type": "Permanent",
"Joining_Date": "06-MAR-2011",
"Salary": 9000
},
{
"Emp_Name": "Rajiv krishna",
"Emp_Designation": "director",
"Emp_Type": "Permanent",
"Joining_Date": "01-MAR-2011",
"Salary": 100000
}
]
The above is in correct JSON Format.
Having received the NSData format of the above, I use the following to convert the same into JSON Dictionary:
NSError *error = nil;
id jsonObject = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONWritingPrettyPrinted error:&error];
NSDictionary *deserializedDictionary = nil;
if (jsonObject != nil && error == nil)
{
if ([jsonObject isKindOfClass:[NSDictionary class]])
{
//Convert the NSData to NSDictionary in this final step
deserializedDictionary = (NSDictionary *)jsonObject;
}
}
However the "deserializedDictionary" is always null or empty. Basically it never came inside the If Loop above.
I have been trying to figure this out for a while and am not able to. Please help

Your json object is an array try with NSArray instead of NSDictionary.

Because the JSON returned is an array, not a dictionary. Try:
NSLog(#"%#", NSStringFromClass([jsonObject class]));

Related

JSON Arrays and Sorting

I have this json array which I have outlined below. I want to know how I could get all the strings under the "name" key only and place in a certain array to be sorted alphabetically by name and later split into further arrays in accordance to the first letter in the names. Any guide to carrying this out will be much appreciated, thanks. I am using the json kit via github and also NSJSONserialization.
{
"proj_name": "Ant",
"id":
[
{
"name": "David"
},
{
"name": "Aaron"
}
]
},
{
"proj_name": "Dax",
"id":
[
{
"name": "Adrian"
},
{
"name": "Dan"
}
]
}
Here is sample that selects just names and sort them alphabetically. Replace responseData with your data object.
NSMutableArray *names = [[NSMutableArray alloc] init];
NSError* error;
NSArray* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
for (NSDictionary *proj in json) {
NSArray *ids = [proj objectForKey: #"id"];
for (NSDictionary *name in ids)
{
[names addObject: [name objectForKey: #"name"];
}
}
NSArray *sortedNames = [names sortedArrayUsingSelector: #selector(localizedCaseInsensitiveCompare:)];
Go to http://json.bloople.net/ in this link you can see the structure of your JSON response.
from the above response i can see the response as follow:
Project name: Dax
id : 0 name : Adrian
1 name : Dan
So you can use the NSjsonserialization class from Apple. No need to use JSON kit.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"Your URL"]]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(#"url=%#",request);
id jsonObject = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:nil];
if ([jsonObject respondsToSelector:#selector(objectForKey:)])
{
Nsstring *projectname=[jsonObject objectForKey:#"proj_name"];
NSArray *name_array=[jsonObject objectForKey:#"id"];
NSLog(#"projectname=%#",projectname);
NSLog(#"name_array=%#",name_array);
}
Assuming you've successfully parsed the JSON into an NSArray, you can simplify things pretty dramatically:
NSArray *names = [parsedArray valueForKeyPath:#"#distinctUnionOfArrays.id.name"];
The names array should now contain all of the names flattened into a single array. To sort them, you could then do:
NSArray *sortedNames = [names sortedArrayUsingDescriptors:#[[NSSortDescriptor
sortDescriptorWithKey:#"description" ascending:YES]]];
Or all at once:
NSArray *sortedNames = [[parsedArray valueForKeyPath:#"#distinctUnionOfArrays.id.name"]
sortedArrayUsingDescriptors:#[[NSSortDescriptor
sortDescriptorWithKey:#"description"
ascending:YES]]];
The sortedNames array would now contain:
<__NSArrayI 0x713ac20>(
Aaron,
Adrian,
Dan,
David
)

How to retrive data from json

I am new to iPhone development. I got json as response.
How to separate the Drug value from the json string below:
{"arrCDrugEntity":
[
{
"DrugID":1,
"Drug":"Benadril",
"Quantity":"",
"Comment":"",
"FunctionStatus":false,
"ResultString":"",
"ErrorString":""
},
{
"DrugID":2,
"Drug":"Dcold",
"Quantity":"",
"Comment":"",
"FunctionStatus":false,
"ResultString":"",
"ErrorString":""
},
{
"DrugID":3,
"Drug":"Dolo",
"Quantity":"",
"Comment":"",
"FunctionStatus":false,
"ResultString":"",
"ErrorString":""
},
{
"DrugID":4,
"Drug":"Paracitamol",
"Quantity":"",
"Comment":"",
"FunctionStatus":false,
"ResultString":"",
"ErrorString":""
},
{
"DrugID":5,
"Drug":"Panadol",
"Quantity":"",
"Comment":"",
"FunctionStatus":false,
"ResultString":"",
"ErrorString":""
},
{
"DrugID":6,
"Drug":"Pudin Hara",
"Quantity":"",
"Comment":"",
"FunctionStatus":false,
"ResultString":"",
"ErrorString":""
}
],
"FunctionStatus":true,
"UserID":-1,
"DeliveryAddress":"",
"ResultString":"",
"ErrorString":""
}
Import SBJson.h in your class and use JSONValue method for converting json string into dictionary.
NSDictionary *dict = [yourJsonString JSONValue];
NSArray *arr = [dict valueForKey:#"arrCDrugEntity"];
NSMutableArray *drugArray = [[NSMutableArray alloc] init];
for (NSDictionary *drug in arr) {
[drugArray addObject:[drug valueForKey:#"Drug"]];
}
NSLog(#"drugArray:%#",drugArray);
I think it will be helpful to you.
NSString *str=#"http://your_web_server/your_file....";
NSURL *url=[NSURL URLWithString:str];
NSData *data=[NSData dataWithContentsOfURL:url];
NSError *error=nil;
id *response=[NSJSONSerialization JSONObjectWithData:data options:
NSJSONReadingMutableContainers error:&error];
NSLog("Your JSON Object: %# Or Error is: %#, response, error);
Following code for retrive json data
Dictionary *json = [myString JSONValue];
// Get the objects you want, e.g. output the second item's client id
NSArray *items = [json valueForKeyPath:#"arrCDrugEntity"];
NSLog(#" client Id : %#", [[items objectAtIndex:1] objectForKey:#"clientId"]);
May this help you
You can use NSJSONSerialization for doing this.
NSData *response = [yourJSONString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: response options: NSJSONReadingMutableContainers error: &err];
First put your JSON through a JSON formatter before pasting it, easier to read, use this website
http://jsonformatter.curiousconcept.com/
Secondly, find good JSON parser, personally I use SBJSON, found here
http://stig.github.com/json-framework/
Once you have that downloaded, quite easy to parse, like this, example below
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"drugData" ofType:#"json"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
NSString *responseString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
NSDictionary *MainJSON = [responseString JSONValue];
NSArray *array = [MainJSON valueForKey:#"arrCDrugEntity"];
for(int i = 0; i < [array count]; i++)
{
NSDictionary *temp = [array objectAtIndex:i];
NSLog(#"%#", [temp valueForKey:#"Drug"]);
}
Edit: Updated loop, better way of parsing it, as means you can loop through each individual drug object, so easier if you want to parse the data into a drug object class if you need to
Use this code
#import "JSONKit.h"
NSDictionary *dictionary = [stringData objectFromJSONString];
NSArray *arrayOfDrugs=[NSArray alloc] initWithArray:[dictionary valueForKey:#"arrCDrugEntity"];
for (NSDictionary *drugDic in arrayOfDrugs)
{
NSLog(#"drug id is :%#",[drugDic valueForKey:#"DrugID"]);
NSLog(#"drug is :%#",[drugDic valueForKey:#"Drug"]);
NSLog(#"Quantity is :%#",[drugDic valueForKey:#"Quantity"]);
NSLog(#"Comment is :%#",[drugDic valueForKey:#"Comment"]);
NSLog(#"FunctionStatus is :%i",[[drugDic valueForKey:#"FunctionStatus"] intValue]);
NSLog(#"ResultString is :%#",[drugDic valueForKey:#"ResultString"]);
NSLog(#"ErrorString is %#",[drugDic valueForKey:#"ErrorString"]);
}
with simple JSON Files
but you have to disable ARC in build setting for JSON file.

Couldn't parse data using Json on IOS 5

I try to grab some data with json on ios 5. but i fail...
could someone help me and tell me why it didn't work out.
here's my implementation code
define :
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
#define kLatestKivaLoansURL [NSURL URLWithString:#"http://jaksport.com/jarray.php"] //2
then in the viewdidload :
NSData* data = [NSData dataWithContentsOfURL:
kLatestKivaLoansURL];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
this is the function:
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* key = [json objectForKey:#"price"]; //2
NSLog(#"value: %#", key); //3
}
this is the json file:
{
"prices":
{
"price":[
{
"id":1,
"name":"Rosie Gradas",
"beer":4.5,
"cider":4.5,
"guinness":4
},
{
"id":2,
"name":"Wicked Wolf",
"beer":5,
"cider":4.5,
"guinness":4
},
{
"id":3,
"name":"Cafe Posh",
"beer":6,
"cider":5.5,
"guinness":5.5
},
{
"id":4,
"name":"My House",
"beer":16,
"cider":15.5,
"guinness":15.5
}
]
}
}
the nslog always print out null value
The error is in how you acces the objects in your JSON :
{
"prices":
{
"price":[
{
"id":1,
"name":"Rosie Gradas",
"beer":4.5,
"cider":4.5,
"guinness":4
}
}
Given a JSON like that to access the price array you use a syntax like this
NSArray *price = [[json objectForKey:#"prices"]objecForkey:#"price"];
Check the URL in web browser, Your URL is Not A proper JSON.
Link for JSON Verification : JSON Verification

How to parse JSON with multiple instance in Object C [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to use NSJSONSerialization
I am testing to use the web service of my website on iphone Application.
The JSON with problem is that:
[
{
"name": "Jason1",
"age": 20
},
{
"name": "Jason2",
"age": 40
},
{
"name": "Jason3",
"age": 60
}
]
And my codes:
NSData *jasonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://localhost:3000/all_personal_information.json"]];
NSDictionary *json = nil;
if (jasonData) {
json = [NSJSONSerialization JSONObjectWithData:jasonData options:kNilOptions error:nil];
}
The code work fine with {"name":"jason","age":20}
and I can get the values by using json[#"name"] and json[#"age"]
But i don't know how to get the value from the JSON with problem.
I tried to use [json enumerateKeysAndObjectsWithOptions] to transverse the dictionary.
But I will get an error:
enumerateKeysAndObjectsWithOptions:usingBlock:]: unrecognized selector sent to instance 0x89b2490
But I can get the full JSON when I Log the [json description] into console.
Take it in an array.. for example
NSData *jasonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://localhost:3000/all_personal_information.json"]];
NSDictionary *json = nil;
if (jasonData) {
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jasonData options:NSJSONReadingMutableContainers error: &e];
}
the array will contain your
{
"name": "Jason1",
"age": 20
}
etc in its individual indexes. when u want to get the values in it, you can use this below method to get the values
NSDictionary *userName = [jsonArray objectAtIndex:1];
NSString *stringName = [userName valueForKey:#"name"];
You're creating a dictionary while you get an array. If you do the following it should work:
id json = nil;
if (jasonData)
{
json = [NSJSONSerialization JSONObjectWithData:jasonData options:kNilOptions error:nil];
}
if ([json isKindOfClass:NSArray.class])
{
for (id personDef in json)
{
if ([personDef isKindOfClass:NSDictionary.class])
{
NSDictionary * dict = (NSDictionary *) moduleDef;
NSString * name = [dict objectForKey:#"name" withClass:NSString.class];
NSLog(#"Person: #%", name);
}
}
}
In here I do some additional checking if the objects are the ones we expect. If this isn't the case you should add (proper) error handling.
it will help you.
NSMutableDictionary *CompaintsAry =[NSJSONSerialization JSONObjectWithData:respo options:kNilOptions error:&error];
NSMutableArray *tempary =[[NSMutableArray alloc]init];
for (int i=0;i < [CompaintsAry count];i++) {
CfResultFatch *rs = [[CfResultFatch alloc] initWithName:[[CompaintsAry obj ectAtIndex:i]objectForKey:#"Name"]
cipd :[[CompaintsAry objectAtIndex:i] objectForKey:#"Age"]];
[tempary addObject:rs];
}
cfComlaintsLists = [[NSMutableArray alloc] initWithArray:tempary];
SelectComplain = [[NSMutableArray alloc] initWithCapacity:[cfComlaintsLists count]];
[chiftab reloadData];

iPhone JSON Parse Problem

I'm working with parsing JSON into my app and am running into some issues pulling in just one section of it. For some reason, it seems to be going through my whole JSON feed, logging NULL values except for the one I specify.
Any advice? Thanks for the help!
My Method:
-(void)loadStats {
NSDictionary *totalsfeed = [self downloadTotals];
NSArray *totals = (NSArray *)[totalsfeed valueForKey:#"totals"];
NSLog(#"NEW TOTALS: %#", [totals valueForKey:#"d_monthly_total"]);
}
Console Results:
2011-08-30 11:35:38.096 App Name [9142:16507] NEW TOTALS: (
"<null>",
"<null>",
2,
"<null>",
"<null>",
"<null>"
)
JSON Feed
{
"totals": [
{
"ab_grand_total": "2217"
},
{
"d_grand_total": "1096"
},
{
"d_monthly_total": "2"
},
{
"ab_monthly_total": "13"
},
{
"ab_yearly_total": "746"
},
{
"d_yearly_total": "233"
}
]
}
I'm parsing the JSON here:
// JSON from Server Actions
- (NSString *)stringWithUrl:(NSURL *)url {
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadRevalidatingCacheData
timeoutInterval:30];
// Fetch the JSON response
NSData *urlData;
NSURLResponse *response;
NSError *error;
// Make synchronous request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
// Construct a String around the Data from the response
return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}
- (id)objectWithUrl:(NSURL *)url {
SBJsonParser *jsonParser = [SBJsonParser new];
NSString *jsonString = [self stringWithUrl:url];
// Parse the JSON into an Object
return [jsonParser objectWithString:jsonString error:NULL];
}
- (NSDictionary *)downloadTotals {
id totals = [self objectWithUrl:[NSURL URLWithString:#"http://example.com/totals.json"]];
NSDictionary *totalsfeed = (NSDictionary *)totals;
return totalsfeed;
}
totals is an NSArray of NSDictionary objects, so [totals valueForKey:#"d_monthly_total"] does not make sense. Instead, to get d_monthly_total, you should do:
NSDictionary *dMonthlyTotalDictionary = (NSDictionary *)[totals objectAtIndex:2];
NSLog(#"NEW TOTALS: %#", [dMonthlyTotalDictionary objectForKey:"d_monthly_total"]);
To iterate through totals, do:
for(NSDictionary *myDict in totals) {
for(NSString *key in myDict) {
NSLog(#"%#: %#", key, [myDict objectForKey:key]);
}
}
Don't you have the NSDictionary and NSArray the wrong way around for the JSON you show here - wouldn't you expect the NSArray to be the outer container?
If you can control your JSON feed, you should merge these totals into a single has, e.g.:
{"ab_grand_total": "2217",
"ab_grand_total": "2217",
"d_grand_total": "1096"
}
and then load it as an NSDictionary instead of an NSArray.