NSMutableArray Not showing actual values when NSLog in iphone application - iphone

I am doing an NSLog of an array but instead of data it shows the following values. I do not know how to fix this issue and get the values from the array
if(!surveyQuestions){
surveyQuestions=[[NSMutableArray alloc]init];
}
Total Survey Questions 3
2012-07-31 08:54:53.555 SQL[442:9203] SurveyQuestions (
"<QuestionData: 0x4da10f0>",
"<QuestionData: 0x4b9f120>",
"<QuestionData: 0x4ba42e0>"
)

I'm not sure what you're trying to do but: it's certain that the poor array object has no idea what and how your own custom class does, its best possibility to print an instance of your class is to call its description method, which you see, and which is not really helpful. You maybe want to do two things:
I. If you only want to print your objects like this, override the description method of your class and use some format string (given that you haven't written a single line of code I have to fall back to guess):
- (NSString *)description
{
return [NSString stringWithFormat:#"Name: %#, address: %#", self.name, self.address];
}
II. If you want to use the data of your class elsewhere, you probably want to loop through its properties manually:
for (QuestionData *d in surveyQuestions)
{
NSLog(#"%#", d.name);
// etc.
}

You need to do something like this:
NSArray *theArray = [[NSArray alloc] initWith...];
NSLog(#"array contents: %#", theArray);

Related

SBJson parsing help iphone

im currently trying to parse some json data on the iphone.
I have been trawling the web for examples, but none seem to suit my purpose, i am using SBJson.
What I want is to be able to get an NSArray of Titles, Artisits, Status, etc. so that I can display them on a table view. Any help would be great, so far all i get is an array of "Values".
JSON = {"values":
[
{"Status":"N", "Filename":"RD207T04", "Title":"Simple Man (Explicit)", "Artist":"DIAFRIX F/DANIEL MERRIWE", "Release":"May11"},
{"Status":"N", "Filename":"CR221T27", "Title":"Midnight City", "Artist":"M83", "Release":"Dec11"},
{"Status":"N", "Filename":"ED211T03", "Title":"I\"ll Be Your Man", "Artist":"JAMES BLUNT", "Release":"Jul11"}
]}
You don't want an array of titles, artists, etc. You want the array of NSDictionarys represented by the values key. Then you can do:
cell.textLabel.text = [[valuesArray objectAtIndex:indexPath.row]valueForKey:#"Title"]];
inside your cellForRowAtIndexPath: delegate method. If you do not have this already, this is how to get that array:
NSArray *valuesArray = [[myJsonString JSONValue]objectForKey:#"values"];
Thanks mate, I was definately over complicating things:
The end code was this:
NSArray *valuesArray = [[playlist JSONValue] objectForKey:#"values"];
NSString *test = [[valuesArray objectAtIndex:0]valueForKey:#"Title"];
NSLog(#"test = %#", test);
Now all I have to do is iterate through the set :)

Why does SBJson JSON parsing only get the last key of interest?

I am using the following JSON: http://www.kb.dk/tekst/mobil/aabningstider_en.json
When I try to parse it by the key "location" as such:
// get response in the form of a utf-8 encoded json string
NSString *jsonString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
// get most parent node from json string
NSDictionary *json = [jsonString JSONValue];
// get key-path from jason up to the point of json object
NSDictionary *locations = [json objectForKey:#"location"];
NSLog( #"%#", locations );
// iterate through all of the location objects in the json
for (NSDictionary *loc in locations )
{
// pull library name from the json object
NSString *name = [loc valueForKey:#"name"];
// add library data table arrays respectively
[ libraryNames addObject: ( ( name == nil | name.length > 0 ) ? name : #"UnNamed" ) ];
}
When I print the the object locations via NSLog:
{
address = "Universitetsparken 4, 3. etage, 2100 K\U00f8benhavn \U00d8";
desc = "";
lastUpdated = "";
latlng = "55.703124,12.559596";
link = "http://www.farma.ku.dk/index.php?id=3742";
name = "Faculty of Pharmaceutical Sciences Library";
parts = {
part = {
hour = {
day = "5.June Constitution Day (Denmark)";
open = Closed;
};
hours = {
hour = {
day = Friday;
open = "10-16";
};
};
name = main;
};
};
}
Which is only the last value for the "location" keys. Am I doing something wrong?
I tried validating the JSON via http://jsonlint.com/, however when I'd put in the JSON URL as above, it said "valid" - still only the last "locations" key was shown", however if I copy-paste it, it will not validate the JSON, and has to be fixed by removing new-lines from the string.
Also, when i try to parse the JSON and get the "name" fields, I get the following exception:
2012-05-08 15:37:04.941 iPhone App Tabbed[563:f803] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0x68bfe70> valueForUndefinedKey:]: this class is not key value coding-compliant for the key name.'
*** First throw call stack:
(0x13dc052 0x156dd0a 0x13dbf11 0x9d2f0e 0x941841 0x940ca9 0x4593 0xf964e 0x114b89 0x1149bd 0x112f8a 0x112e2f 0x1148f4 0x13ddec9 0x365c2 0x3655a 0x25b569 0x13ddec9 0x365c2 0x3655a 0xdbb76 0xdc03f 0xdbbab 0x25dd1f 0x13ddec9 0x365c2 0x3655a 0xdbb76 0xdc03f 0xdb2fe 0x5ba30 0x5bc56 0x42384 0x35aa9 0x12c6fa9 0x13b01c5 0x1315022 0x131390a 0x1312db4 0x1312ccb 0x12c5879 0x12c593e 0x33a9b 0x281d 0x2785)
terminate called throwing an exception(lldb)
It would make more sense if the "locations" tag was an array object enclosed by square brackets ([]), however right now it's only an sequence of normal key-value pairs... Sadly, that's the JSON I have to work with.
Please help and thanks a great deal! :)
Sincerely,
Piotr.
The JSON you've got to work with may be valid, but it doesn't make much sense. It has one big dictionary with the location key repeated many times. Most JSON parser will simply return the last value for the repeated key. It would be best if you could change the structure to use an array instead, but if you cannot there's still hope. You can read the stream and stuff the values from the location keys into an array as they come out of it. This is how you'd do that:
#interface BadJsonHelper : NSObject
#property(strong) NSMutableArray *accumulator;
#end
#implementation BadJsonHelper
- (void)parser:(SBJsonStreamParser *)parser foundArray:(NSArray *)array {
// void
}
- (void)parser:(SBJsonStreamParser *)parser foundObject:(NSDictionary *)dict {
[accumulator addObject:dict];
}
#end
You can drop that little helper class at the top of your file, outside the #implementation section of the class where you're doing your work. (There's no need for the #interface and #implementation being in different files.)
In your code, you would use it like this:
BadJsonHelper *helper = [[BadJsonHelper alloc] init];
helper.accumulator = [NSMutableArray array];
SBJsonStreamParserAdapter *adapter = [[SBJsonStreamParserAdapter new] init];
adapter.delegate = helper;
adapter.levelsToSkip = 1;
SBJsonStreamParser *parser = [[SBJsonStreamParser alloc] init];
parser.delegate = adapter;
switch ([parser parse: responseData]) {
case SBJsonStreamParserComplete:
NSLog(#"%#", helper.accumulator);
break;
case SBJsonStreamParserWaitingForData:
NSLog(#"Didn't get all the JSON yet...");
break;
case SBJsonStreamParserError:
NSLog(#"Error: %#", parser.error);
break;
}
This example was originally adapted from the following test:
https://github.com/stig/json-framework/blob/master/Tests/StreamParserIntegrationTest.m
Update: I created a fully functional example project that loads the JSON asynchronously and parses it. This is available from github.
The JSON is valid, however there is a basic problem regarding the definition of the array of items.
Instead of defining an array of locations using brackets, the JSON redefines the same location key/value pair over and over again. In other words JSON initially says the value of location is the collection with name "The Black Diamond", but immediately after it redefines it with the collection with name "Faculty Library of Humanities" and so on till the last location Faculty of Pharmaceutical Sciences Library".
The same is true for parts and hours.
If you can't fix the result of the JSON and you really need to get it working you may want to modify the JSON removing the "location" keys and adding brackets properly.
Edit
Alternatively you may use an NSScanner and process the JSON result manually. Kinda hacky but it will work as long as the JSON format doesn't change significantly.
Edit
This snipped of code should do the work...
NSString *jsonString = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
int indx = 1;
for (;;)
{
NSRange locationRange = [jsonString rangeOfString:#"\"location\":"];
if (locationRange.location == NSNotFound) break;
jsonString = [jsonString stringByReplacingCharactersInRange:locationRange
withString:[NSString stringWithFormat:#"\"location%d\":", indx++]];
}
NSDictionary *locations = [json objectForKey:#"location"];
As you can see, the result of JSON parsing by SBJson is a NSDictionary. A dictionary contains key/value pairs, and the keys are unique identifiers for the pairs.
The JSON data you need to handle is valid but not a good one. Per RFC 4627 - 2.2:
An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique.
Things like jQuery can parse the JSON also, but the result is the same as SBJson (the last one as the one). See Do JSON keys need to be unique?.
It is not a MUST, but it's still not a good practice. It would be much easier if you are able to change the structure of the JSON data on the server side (or even on the client side after receiving it) rather than parsing it as is.

parsing JSON object and sub-elements on iphone app

I am building an app that uses a UPC data base API. I am getting back a JSON object, example from here: http://www.simpleupc.com/api/methods/FetchNutritionFactsByUPC.php
{
"success":true,
"usedExternal":false,
"result"
{
"calories_per_serving":"150",
"cholesterol_per_serving":"15",
"cholesterol_uom":"Mg",
"dvp_calcium":"30",
"dvp_cholesterol":"4",
"dvp_iron":"2",
"dvp_protein":"17",
"dvp_saturated_fat":"8",
"dvp_sodium":"10",
"dvp_total_fat":"4",
"dvp_vitamin_a":"10","
"dvp_vitamin_c":"0",
"dvp_vitamin_d":"25",
"fat_calories_per_serving":"25",
"fiber_per_serving":"<1",
"fiber_uom":"G",
"ingredients":"Fat Free Milk, Milk, Sugar, Cocoa (Processed With Alkali),
Salt, Carrageenan, Vanillin (Artificial Flavor),
Lactase Enzyme, Vitamin A Palmitate And Vitamin D3.",
"protein_per_serving":"8",
"protein_uom":"G",
"size":"240",
"units":"mL",
"servings_per_container":"8",
"sodium_per_serving":"230",
"sodium_uom":"Mg",
"total_fat_per_serving":"2.5",
"total_fat_uom":"G",
"trans_fat_per_serving":"0",
"trans_fat_uom":"G",
"upc":"041383096013"
}
}
My problem is with parsing the "ingredients" element, which is a sub list of the object dictionary.
How would you suggest parsing the ingredients list? If I could get it to an NSArray, assuming commas are separators, that would have been great.
I tried to do this, but looks like its just a string, so no way to parse it.
Any suggestion would be more than welcome. Thanks!
//Thats the whole JSON object
NSDictionary *json_dict = [theResponseString JSONValue];
//Getting "results" which has all the product info
NSArray *myArray = [[NSArray alloc] init];
myArray = [json_dict valueForKey:#"result"];
Now how do I get "ingredients" from myArray in an array form?
You're getting result as an array, but (in JSON terminology) it's not an array. It's an object, so use an NSDictionary. Something like this:1
NSDictionary *result = [json_dict objectForKey:#"result"];
Then you can get the inner ingredients object from that:
NSString *ingredients = [result objectForKey:#"ingredients"];
Edited as per #Bavarious' comment.
1Apologies for glaring errors, as I'm not terribly well-versed in Objective-C. You might need to allocate memory for the returned NSDictionary and NSString pointers; I'm not sure.
Here's all you need to do:
NSDictionary *json_dict = [theResponseString JSONValue];
// Use a key path to access the nested element.
NSArray *myArray = [json_dict valueForKeyPath:#"result.ingredients"];
EDIT
Whoops, Matt's right. Here's how to deal with the string value:
// Use a key path to access the nested element.
NSString *s = [json_dict valueForKeyPath:#"result.ingredients"];
NSArray *ingredients = [s componentsSeparatedByString:#", "];
Note that you might need to trim the '.' character off the last element of the array.

Get objects from a NSDictionary

I get from an URL this result :
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
it looks like this :
[{"modele":"Audi TT Coup\u00e9 2.0 TFSI","modele_annee":null,"annee":"2007","cilindre":"4 cyl","boite":"BVM","transmision":"Traction","carburant":"ES"},
{"modele":"Audi TT Coup\u00e9 2.0 TFSI","modele_annee":null,"annee":"2007","cilindre":"4 cyl","boite":"BVM","transmision":"Traction","carburant":"ES"}]
So it contains 2 dictionaries. I need to take the objects from all the keys from this result. How can I do this?
I tried this : NSDictionary vehiculesPossedeDictionary=(NSDictionary *)result;
and then this : [vehiculesPossedeDictinary objectForKey:#"modele"]; but this is not working.
Please help me... Thanks in advance
What you have is a JSON string which describes an "array" containing two "objects". This needs to be converted to Objective-C objects using a JSON parser, and when converted will be an NSArray containing two NSDictionarys.
You aren't going to be able to get your dictionary directly from a string of JSON. You are going to have to going to have to run it through a JSON parser first.
At this point, there is not one build into the iOS SDK, so you will have to download a third-party tool and include it in your project.
There are a number of different JSON parser, include TouchJSON, YAJL, etc. that you can find and compare. Personally, I am using JSONKit.
#MatthewGillingham suggests JSONKit. I imagine it does fine, but I've always used its competitor json-framework. No real reason, I just found it first and learned it first. I do think its interface is somewhat simpler, but plenty of people do fine with JSONKit too.
Using json-framework:
require JSON.h
...and then
NSString *myJsonString = #"[{'whatever': 'this contains'}, {'whatever', 'more content'}]";
NSArray *data = [myJsonString JSONValue];
foreach (NSDictionary *item in data) {
NSString *val = [item objectForKey:#"whatever"];
//val will contain "this contains" on the first time through
//this loop, then "more content" the second time.
}
If you have array of dictionary just assign objects in array to dictionary like
NSDictionary *dictionary = [array objectAtIndes:0];
and then use this dictionary to get values.

NSMutableArray Strings changing after reading in from file

I have a NSMutableArray that I create on program load. If the program terminates, I save the array to a file. Then when the app starts again, I check to see if this file exists and if so, read it in as the array.
Problem is, on first creation everything is fine, I check an array object against a certain string and if it is equal, do something. This works fine on first go. But if I read the array back in from the fine, and do the same compare, even though they both say they are the same, it does not think so and skips the process. Code example:
This is if the file does not exist, create from scratch:
NSMutableArray *tmpArray=[[NSMutableArray alloc] initWithObjects:
#"1000",
#"1000",
#"1000",
#"500",
#"500",
#"500",
#"250",
#"250",
#"250",
#"100",
#"100",
#"100",
#"100",
#"TRIPLE",
#"TRIPLE",
#"DOUBLE",
#"DOUBLE",
#"- 500",
#"- 250",
#" - 250",
#"- 100",
#"- 100",
#"HALF",
#"BUST",
nil];
if file does exist:
pnames = [[NSMutableArray alloc] initWithContentsOfFile:myPath];
Here is where the compare comes in:
NSString *strInfo;
strInfo = [pnames objectAtIndex: theInteger - 1];
NSLog(#"strInfo: %#", strInfo);
if (strInfo == #"DOUBLE")
{
//do something
}
Like I said, this compare works fine on the first creation, but not when the array is loaded via the file.
Writing the file out is done via:
(void)applicationWillTerminate:(UIApplication *)application {
[pnames writeToFile:[self saveFilePath] atomically:YES];
}
When I look in the debugger at the strInfo (from above), it shows as:
NSCFString - 0c8168 - DOUBLE ---From creation, and does recognize it as equal
NSCFString - 0x3d42af0 - DOUBLE ---When it does not recognize it as equal, via file load
Any insight on this is greatly appreciated.
Geo...
if (strInfo == #"DOUBLE")
{
//do something
}
You can't compare NSString instances using ==, you need to use -isEqualToString:.
if ([strInfo isEqualToString: #"DOUBLE"]) { ... }
It happens to work on first creation because all of the string values are compiled into your app as constant strings and, thus, the #"DOUBLE" that is in your array just so happens to be at the same address as the #"DOUBLE" of the comparison.
When the array is read from "disk", new strings are allocated.
I wonder if you just saved this NSString to the NSUserDefaults you'd have a much easier time. Keep in mind, when you save a Mutable string to NSUserDefaults, when you retrieve it, its not mutable.
I'm not sure of your exact problem, but this might make things easier.