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

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

Related

NSDictionary to NSString JSON

I am trying to wrap my head around pulling a keys value from a JSON array and saving it as a String for comparison later: The following code makes my app crash when it gets to this section of code. I don't understand why.
My json array looks like so:
[{"User_Id":"CRNA000099","User_Name":"jbliz","User_Fname":"Julia"}]
My xcode:
userarray_login = [NSJSONSerialization JSONObjectWithData:dataURL options:kNilOptions error:&error];
NSDictionary* userType = [userarray_login objectForKey:#"User_Name"];
NSString *userPermission = [userType objectAtIndex:0];
if ([userPermission isEqualToString:#"jbliz"])
{
NSLog(#"I should get the avalue here: %#", userPermission);
}
I am confused between NSDictionary and NSString. Any feedback would be a
NSMutableArray *name=[[[NSMutableArray alloc] initWithArray:[userarray_login valueForKey:#"User_Name"]]retain];
// Get the only all Names into name Array from json Array
NSString *userPermission = [name objectAtIndex:0]; // get the first name from Array
if ([userPermission isEqualToString:#"jbliz"])
{
NSLog(#"I should get the avalue here: %#", userPermission);
}
Json Array : [{"User_Id":"CRNA000099","User_Name":"jbliz","User_Fname":"Julia"},{},...] an array contains Dictionaries.
for this try like,
NSArray * userarray_login = [NSJSONSerialization JSONObjectWithData:dataURL options:kNilOptions error:&error];
for (NSDictionary * dict in userarray_login) {
NSString * name = [dict objectForKey:#"User_Name"];
if ([name isEqualToString:#"jbliz"]) {
NSLog(#"Value is here: %#", name);
}
}
Your json has array of Dictionary you need to follow below steps,
//NSJSONSerialization return you array in userarray_login
userarray_login = [NSJSONSerialization JSONObjectWithData:dataURL options:kNilOptions error:&error];
//You fetch Dictionary from the array
NSDictionary* userType = [userarray_login objectAtIndex:0];
//Fetch NSString value using keyValue
NSString *userPermission = [userType objectForKey:#"User_Name"];
//String comparison
if ([userPermission isEqualToString:#"jbliz"])
{
NSLog(#"I should get the avalue here: %#", userPermission);
}
This is correct code for your stuff.

Converting JSON Data from NSData to NSDictionary

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

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
)

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.

Using JSON Framework on iPhone - HELP!

Currently I am using the following code to parse the JSON link sent. This is how I also send a GET call to the Google Reader API for an upcoming iPhone application of mine.
- (NSArray *)subscriptionList
{
if(!cookies && [cookies count] == 0) {
[self requestSession];
}
NSString * url = #"http://www.google.com/reader/api/0/subscription/list?output=json&client=scroll";
ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
[request setRequestMethod:#"GET"];
[request setRequestCookies:cookies];
[request addRequestHeader:#"Authorization" value:[NSString stringWithFormat:#"GoogleLogin auth=%#", [self auth]]];
[request startSynchronous];
subfeeds = [NSMutableArray array];
// Create new SBJSON parser object
SBJSON *parser = [[SBJSON alloc] init];
if ([request responseStatusCode] == 200) {
NSData * sixty = [request responseData];
NSString * body = [[NSString alloc] initWithData:sixty encoding:NSUTF8StringEncoding];
if (body) {
NSArray *feeds = [parser objectWithString:body error:nil];
NSLog(#"Array Contents: %#", [feeds valueForKey:#"subscriptions"]);
NSLog(#"Array Count: %d", [feeds count]);
NSDictionary *results = [body JSONValue];
NSArray *ohhai = [results valueForKey:#"subscriptions"];
for (NSDictionary *title in ohhai) {
subTitles = [title objectForKey:#"title"];
NSLog(#"title is: %#",subTitles);
}
}
}
return subfeeds;
[subTitles release];
[parser release];
}
I can successfully parse the JSON using the above code, and it successfully outputs the titles into NSLog. In my RootViewController.m, I call the following to grab this -(NSArray *)subscriptionList.
-(void)viewDidAppear:animated {
GoogleReader * reader = [[GoogleReader alloc] init];
[reader setEmail:gUserString];
[reader setPassword:gPassString];
//feedItems is a NSArray where we store the subscriptionList NSArray
feedItems = [reader subscriptionList];
//NSString *feedTitle = [];
NSLog(#"%#", feedItems);
[reader release];
// the rest of the function
}
The code above successfully works with the credentials entered. As you can see there is also a commented NSString called feedTitle. This is where I want to pull the #"title" from the parsed JSON but I do not know how to call it.
Any help would be greatly appreciated!
This is what the JSON source looks like:
{"subscriptions":
[
{"id":"","title":"","categories":[],"sortid":"","firstitemmsec":""},
{"id":"","title":"","categories":[],"sortid":"","firstitemmsec":""},
{"id":"","title":"","categories":[],"sortid":"","firstitemmsec":""},
{"id":"","title":"","categories":[],"sortid":"","firstitemmsec":""},
{"id":"","title":"","categories":[],"sortid":"","firstitemmsec":""}
]
}
I'm interested in only the "title" node.
Well, it would help if you added the source JSON but it's quite easy to grasp how SBJSON parses incoming JSON.
Just an example:
{ "myOutDict" : { "key1": "val1" , "key2" : "val2"} }
This JSON String would be parsed so you can access it by using this code
NSDictionary* myOuterdict = [feeds valueForKey:#"myOutDict"]);
NSString* val1 = [myOuterdict valueForKey:#"key1"]);
NSString* val2 = [myOuterdict valueForKey:#"key2"]);
Edit: Checked my personal Google Reader feed:
The JSON looks like this
{
"subscriptions": [{
"id": "feed/http://adambosworth.net/feed/",
"title": "Adam Bosworth's Weblog",
"categories": [],
"sortid": "0B5B845E",
"firstitemmsec": "1243627042599"
},
{
"id": "feed/http://feeds.feedburner.com/zukunftia2",
"title": "Zukunftia",
"categories": [],
"sortid": "FCABF5D4",
"firstitemmsec": "1266748722471"
}]
}
So the corresponding Objective C Code would be:
NSArray* subscriptions= [feeds valueForKey:#"subscriptions"]);
foreach(NSDictionary* item in subscriptions) {
// Do stuff
// NSString* title = [item valueForKey:#"title"]
// NSString* id = [item valueForKey:#"id"]
}
I'm not sure I understand the question. Are you trying to get a title for the feed as a whole, or per-item? Because I can't see a title property for the subscriptions array in the source JSON.