xcode counting JSON items - iphone

I need to Count the number of Items (post) in this JSON response,
2012-06-04 14:09:57.872 horitable[72261:11903] JSON : {
posts = (
{
post = {
eventdate = "2012-03-31";
eventid = 2;
eventimage = "http://hernandoz.local/~hernandoz/kopict/02_31march2012.jpg";
eventinfo = "02 event";
eventname = "xplosion 02";
};
},
{
post = {
eventdate = "2012-07-07";
eventid = 3;
eventimage = "http://hernandoz.local/~hernandoz/kopict/greg_vs_turner.jpg";
eventinfo = "02 event";
eventname = "Xplosion 02";
};
},
{
post = {
eventdate = "2012-04-29";
eventid = 4;
eventimage = "http://hernandoz.local/~hernandoz/kopict/ko_itclub_apr_2012.jpg";
eventinfo = "KO East London Interclub";
eventname = "KO Interclub";
};
}
);
}
I know there are only 3 events (post), this is the code I am using
[[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
NSLog(#"JSON : %#", JSON); //get the JSON response
// 6.1 - Load JSON into internal variable
jsonResponse = JSON;
// 6.2 - Get the number of shows (post)
int shows = 0;
for (NSDictionary* day in jsonResponse) {
shows += [[day objectForKey:#"posts"] count];
NSLog(#"count : %d",shows);
}
I get an error , but I don't understand why .
-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x76986f0
can someone please help me out . Thanks

try this
NSLog(#"Response members= %#",responseString);
NSArray *array = [(NSDictionary*)[responseString JSONValue] objectForKey:#"posts"];
NSLog(#"Count value= %d",[array count]);

in your case you can do this
[[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
NSLog(#"JSON : %#", JSON); //get the JSON response
// 6.1 - Load JSON into internal variable
jsonResponse = JSON;
// 6.2 - Get the number of shows (post)
int shows = [[jsonResponse objectForKey:#"posts"] count];
NSLog(#"count : %d",shows);

you need to first fragmentize json as
NSDictionary * dict = [JSON JSONValue];
or
NSDictionary * dict = [JSON JSONFragmentValue];
then
for (NSDictionary* day in dict) {
shows += [[day objectForKey:#"posts"] count];
NSLog(#"count : %d",shows);
}

The problem was JSON as an ID, this works
jsonResponse = [(NSDictionary*)JSON objectForKey:#"posts"];

I think you are mistakely put "posts" instead of "post". The key "posts" contain an array of dictionary, and each dictionary has a key "post". What you are doing is you take all dictionaries from array in lines
for (NSDictionary* day in jsonResponse) {
and check for an key "posts" in dictionary. Really, there is no key called "posts" in dictionary. I is "post". And the value for "post" is a NSDictionary not an array. So you cant call count there. The solution for your issue is remove un-necessary APIs inside for loop
[[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
jsonResponse = JSON;
int shows = 0;
for (NSDictionary* day in jsonResponse) {
shows += 1;
}
NSLog(#"count : %d",shows);

Related

Array not get data for particular key

Response array like this
NewDataSet = {
Table = (
{
City = {
text = "\nThiruvananthapuram";
};
Country = {
text = "\n\nIndia";
};
text = "\n";
},
{
City = {
text = "\nVellore";
};
Country = {
text = "\n\nIndia";
};
text = "\n";
}
);
text = "\n";
I have write this code..
xmlDictionary = [XMLReader dictionaryForXMLString:xmlResultString error:nil];
NSLog(#"%#",xmlDictionary);
NSLog(#"%#",xmlDictionary);
NSArray * responseArr = xmlDictionary[#"NewDataSet"];
NSLog(#"%#",responseArr);
for(NSDictionary * dic in responseArr)
{
NSLog(#"%#",dic);
//[array1 addObject:[dic valueForKey:#"City"]];
[array1 addObject:[[dic valueForKey:#"City"] valueForKey:#"text"]];
}
but not get the data. in array1. please help me out this thanks in advance.
Problem is i will not get the value in NSDictionary.
Error log is
this class is not key value coding-compliant for the key City.'
I got my Solution problem is i will not get the direct City key. Because City key is under the NewDataSet & Table
so first you go to the NewDataSet and then Table key then finally you get the City key.
Now get array data from Dictionary Like
NSArray * City=[[NSArray alloc]init];
City=[[[xmlDictionary valueForKey:#"NewDataSet"] valueForKey:#"Table"] valueForKey:#"City"];
NSLog(#"%#",City);
pass multiple keys inside key this is the solution.
It seems you haven't allocated array1 anywhere,
Your solution goes here:
array1 = [[NSMutableArray alloc]init];
for(NSDictionary * dic in responseArr)
{
[array1 addObject:[dic valueForKey:#"City"]];
}
NSLog(#"array1 >> %#",array1);
If you have already allocated array1, then please try to log the value for [dic valueForKey:#"City"].
try this code...
for(int i =0;i<[responseArr count];i++)
{
NSString *str = [[responseArr objectAtIndex:i] valueForKey:#"City"];
[array1 addObject:str];
}
let me know it is working or not!!!
Happy Coding!!!
array1 = [[NSMutableArray alloc]init];
for(NSDictionary * dic in responseArr)
{
[array1 addObject:[dic objectForKey:#"City"]];
}
NSLog(#"array1 >> %#",array1);
Try this

Parse json_encoded data into an array to be used for a UIPickerView - Xcode

I'm looking to populate an array to be used in a pickerview. The data for the array is generated from a database table.
I have the following JSON_ENCODED array (created in php):
{"result":
[
{"id":"3","quivername":"Kite Boarding"},
{"id":"4","quivername":"Live and Die in LA"},
{"id":"14","quivername":"Bahamas Planning"},
{"id":"15","quivername":"My Trip to India"},
{"id":"16","quivername":"Snowboarding"}
]
}
UPDATE FOR WEBSERVICE PHP CODE
I run this function as a webservice:
passport($_SESSION['IdUser'])
function passport($userid) {
$result = query("SELECT id, quivername FROM quivers WHERE userid = $userid");
if (!$result['error']) {
print json_encode($result);
} else {
errorJson('Can not get passports');
}
}
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
I USE THIS CODE IN XCODE TO CONNECT TO THE WEBSERVICE/WEBSITE USING NSNetworking...
-(void)getPassports {
//just call the "passport" command from the web API
[[API sharedInstance] commandWithParams:[NSMutableDictionary dictionaryWithObjectsAndKeys:
#"passport",#"command",
nil]
onCompletion:^(NSDictionary *json)
{
//got passports, now need to populate pickerArray1
if (![json objectForKey:#"error"])
{
//success, parse json data into array for UIPickerview
}
else
//error, no passports
{
// error alert
}
}];
}
I need the following:
1) how can i populate an NSMutable array with the quivername value? I'm trying to get the result to look like this:
pickerArray1 = [[NSMutableArray alloc] initWithObjects:#"Kite Boarding",
#"Live and Die in LA", #"Bahamas Planning", #"My Trip to India", #"Snowboarding",
nil];
I'm assuming I need to run a for loop which would require me to "count" the number of rows in the array first, but I'm not sure. I don't know how to count the number of rows in the json_array or create an NSMutable array.
Thanks in advance...
You should be able to get your NSData from the URL that returns the JSON using [NSData dataWithContentsOfURL:yourURLValue], then pass the data and parse using something similar to what's below based on your JSON:
//INVOKE WEB SERVICE QUERY IN VIEW DID LOAD -- RUNS ASYNC SO WONT BLOCK UI
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:
#"URLOFYOURWEBSERVICE"]; // <-- may need to cast string to NSURL....
NSMutableArray *quivernames = [self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
});
}
- (NSMutableArray *)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
//ARRAY OR DICT DEPENDING ON YOUR DATA STRUCTURE
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
//ITERATE AND/OR ADD OBJECTS TO YOUR NEW ARRAY
NSMutableArray* JSONResultValues = [json objectForKey:#"yourKey"];
NSMutableArray* resultValues = [[NSMutableArray alloc] init];
for(int x = 0; x< [JSONResultValues count]; x++){
NSDictionary *tempDictionary = [JSONResultValues objectAtIndex:x];
[resultValues addObject:[tempDictionary objectForKey:#"quivername"]];
}
NSLog(#"Results Count: %#", [JSONResultValues count]);
NSLog(#"Results Count: %#", [resultValues count]);
return resultValues;
}
EDIT: For more info check out this explanation for JSON parsing http://www.raywenderlich.com/5492/working-with-json-in-ios-5
You could try this (untested):
//convert this to NSData, not sure how it is getting into obj-c
{"result":[
{"id":"3","quivername":"Kite Boarding"},
{"id":"4","quivername":"Live and Die in LA"},
{"id":"14","quivername":"Bahamas Planning"},
{"id":"15","quivername":"My Trip to India"},
{"id":"16","quivername":"Snowboarding"}
]};
NSMutableArray* myData = [self fetchedData:responseData];
- (NSMutableArray* )fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error
];
NSMutableArray* quivers = [json objectForKey:#"result"];
return quivers;
}
Wenderlich explains it here...

How to get values from unknown key in NSDictionary iphone?

I have one more big problem while parse the values from Webservice response. I dont know the key for the values in the webservice response. For example,
class = (
{
"ObjectiveC" =
(
{
"brief_desc" = "ObjectiveC";
date = "2008-02-27";
"event_status" = Attended;
},
{
"brief_desc" = "ObjectiveC";
date = "2008-03-05";
"event_status" = Attended;
},
{
"brief_desc" = "ObjectiveC";
date = "2008-03-12";
"event_status" = Missed;
},
);
},
{
"Java" = (
{
"brief_desc" = "Java";
date = "2008-02-27";
"event_status" = Attended;
},
{
"brief_desc" = "Java";
date = "2008-03-05";
"event_status" = Attended;
},
{
"brief_desc" = "Java";
date = "2008-03-12";
"event_status" = Missed;
},
);
}
);
In this response even we dont know the keys "ObjectiveC" and "Java". The keys("ObjectiveC and Java") should be change in every response retured. How to get values of key (Unknown key)? How can i parse this response and get the values?
I would enumerate through the keys to get the value. Here is an example of enumeration in objective-c.
NSEnumerator *enumerator = [myDictionary keyEnumerator];
id key;
while ((key = [enumerator nextObject])) {
//assuming value will be string
NSString *valueForKey = [myDictionary valueForKey:key];
//assuming value is another dictionary
NSDictionary *subDictionary = [myDictionary objectForKey:key];
}
And if you don't know the keys of the sub dictionaries, you can enumerate through those as well.
NSDictionary has - (NSArray *)allKeys and - (NSArray *)allValues. One of those might help
NSDictionary * lessonDict = [[NSDictionary alloc] initWithObjectsAndKeys:#"Key", #"Value", #"Key 2", #"Value 2", nil];
NSArray *values = [lessonDict allValues];
NSArray *keys = [lessonDict allKeys];
NSLog(#"Keys: %#",keys);
NSLog(#"Values: %#",values);

How I can iterate and get all values in a NSDictionary?

I have a problem.
I am using the XMLReader class to get a NSDictionary and everything works fine. But i can't to get the values of the atributes of my productData element.
Specifically, I have the following NSDictionary:
{
response = {
products = {
productsData = (
{
alias = "Product 1";
id = 01;
price = "10";
},
{
alias = "Product 2";
id = 02;
price = "20";
},
{
alias = "Product 3";
id = 03;
price = "30";
});
};
};
}
I used this code to create de NSDictionary:
NSDictionary *dictionary = [XMLReader dictionaryForXMLData:responseData error:&parseError];
and responseData contains:
<application>
<products>
<productData>
<id>01</id>
<price>10</price>
<alias>Product 1</alias>
</productData>
<productData>
<id>02</id>
<price>20</price>
<alias>Product 2</alias>
</productData>
<productData>
<id>02</id>
<price>20</price>
<alias>Product 3</alias>
</productData>
</products>
</application>
Then, i don't know how get the values of each productData like id, price and alias...
Anybody know how to do it??
Thanks and please forgive my bad english !
NSArray* keys = [theDict allKeys];
for(NSString* key in keys) {
id obj = [theDict objectForKey:key];
// do what needed with obj
}
you could try something like this :
NSArray* keys = [theDict allKeys];
for(NSString* key in keys) {
if ([key isEqualToString:#"product"]) {
NSArray* arr = [theDict objectForKey:key];
// do what needed with arr
}
}
There is a method on NSDictionary - -allValueswhich returns a new array containing the dictionary’s values. Maybe that will help.
Starting with
NSDictionary *dictionary = [XMLReader dictionaryForXMLData:responseData error:&parseError];
you can do something like this:
NSDictionary *application = [dictionary objectForKey:#"application"];
if ([[application objectForKey:#"products"] isKindOfClass [NSArray class]]) {
NSArray *products = [application objectForKey:#"products"];
for (NSDictionary *aProduct in products) {
// do something with the contents of the aProduct dictionary
}
else if {[[application objectForKey:#"products"] isKindOfClass [NSDictionary class]]) {
// you will have to see what the returned results look like if there is only one product
// that is not in an array, but something along these lines may be necessary
// to get to a single product dictionary that is returned
}
I have had a case similar to this (parsing JSON) where an array was not returned for a signle value, so the result had to be checked for both an array (of product dictionaries in your case) or a single NSDictionary (the product dictionary in your case).

Trouble reading JSON object using Obj-C

I am trying to read the following json object using the json-framework and obj-C
{
Sections = {
Now = "Wednesday 9 February 2011 02:40";
Section = (
{
Article = (
{
Exceprt = "text here";
ID = 49011;
Title = "text here";
Type = Politics;
audioCounter = 0;
commentsCounter = 0;
hasMore = false;
important = False;
likesCounter = 0;
photoCounter = 0;
time = "21:12";
timeStamp = "2/8/2011 9:14:16 PM";
timeStatus = True;
videoCounter = 0;
viewsCounter = 0;
},
{
Exceprt = "text here";
ID = 49010;
Title = "text here";
Type = Politics;
audioCounter = 0;
commentsCounter = 0;
hasMore = false;
important = True;
likesCounter = 0;
photoCounter = 0;
time = "20:45";
timeStamp = "2/8/2011 9:10:59 PM";
timeStatus = True;
videoCounter = 0;
viewsCounter = 0;
},
{
Exceprt = "text here";
ID = 49008;
Title = "text here";
Type = Politics;
audioCounter = 0;
commentsCounter = 0;
hasMore = false;
important = False;
likesCounter = 0;
photoCounter = 0;
time = "20:28";
timeStamp = "2/8/2011 9:09:44 PM";
timeStatus = True;
videoCounter = 0;
viewsCounter = 0;
}
);
ID = 22;
Name = "EN Live";
totalNews = 3416;
}
);
};
}
My intent is to have a list of the articles (list of dictionaries) so that I can later access them easily. I have been stuck a while on this and my code is giving me an error about calling a non existent method for NSArray which has led me to suspect that I am misunderstanding the json object. I am totally new to this and any help is greatly appreciated.
Here's my code:
NSDictionary *results = [jsonString JSONValue];
NSDictionary *Articles = [[results objectForKey:#"Sections"] objectForKey:#"Section"];
NSArray *ListOfArticles = [Articles objectForKey:#"Article"];
for (NSDictionary *article in ListOfArticles)
{
NSString *title = [article objectForKey:#"Title"];
NSLog(title);
}
Thanks !
First of all, those aren’t valid JSON data. Names (in name/value pairs) are strings and must be quoted. String values must always be quoted. Boolean values must be either true or false (lowercase). Check http://json.org/ and http://www.ietf.org/rfc/rfc4627.txt?number=4627 and http://jsonlint.com
Here’s the structure of your data:
The top level value is an object (dictionary)
This object has a name (key) called Sections whose value is itself another object (dictionary)
Sections has a name (key) called Section whose value is an array
Each element in the Section array is an object (dictionary)
Each element in the Section array has a name (key) called Article whose value is an array, as well as other names (keys): ID, title, totalNews
Each element in the Article array is an object
If your JSON data were valid, you could parse them as follows:
// 1.
NSDictionary *results = [jsonString JSONValue];
// 2.
NSDictionary *sections = [results objectForKey:#"Sections"];
// 3.
NSArray *sectionsArray = [sections objectForKey:#"Section"];
// 4.
for (NSDictionary *section in sectionsArray) {
// 5.
NSLog(#"Section ID = %#", [section objectForKey:#"ID"];
NSLog(#"Section Title = %#", [section objectForKey:#"Title"];
NSArray *articles = [section objectForKey:#"Article"];
// 6.
for (NSDictionary *article in articles) {
NSLog(#"Article ID = %#", [article objectForKey:#"ID"];
NSLog(#"Article Title = %#", [article objectForKey:#"Title"];
// …
}
}
Your JSON framework is probably parsing out an NSDictionary where you're expecting an NSArray. It'll let you assign an NSDictionary to an NSArray, but then you'll get a runtime exception when you attempt to call a method on your "array". Judging by the JSON you posted (which isn't correct JSON), this is what I would have my parsing code look like. The names of the NSDictionaries and NSArrays are simply named after the JSON attributes they represent.
NSDictionary* results = [jsonString JSONValue];
NSDictionary* sections = [results valueForKey:#"Sections"];
NSArray* section = [sections valueForKey:#"Section"];
NSArray article = [[section objectAtIndex:0] valueForKey:#"Article"];
for (NSDictionary* anArticle in article) {
NSLog(#"%#", [anArticle valueForKey:#"Title"]);
}