I am trying to loop over a neatest NSDictionary within a NSDictionary.
currently I have this and this returns the first NSDictionary items
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response
for (NSString *tempObject in json ) {
NSLog(#"Single element: %#", tempObject);
}
The Above works fine
however I wish to read a array layer lower and the blow is failing,
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
for (id tempObject in json ) {
NSLog(#"Object: %#, Key: %#", [json objectForKey:tempObject], tempObject);
}
Thanks Mich
It's always good to check whether the deserialized object contains ARRAY or DICTIONARY within. You can check the type of object before trying to access it. Something like this.
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
for (id jsonObject in json ) {
NSLog(#"Object: %#, Key: %#", [json objectForKey:tempObject], tempObject);
if ([jsonObject isKindOfClass:[NSDictionary class]]){
NSDictionary *deserializedDictionary = jsonObject;
NSLog(#"Deserialized JSON Dictionary = %#",
deserializedDictionary);
}
else if ([jsonObject isKindOfClass:[NSArray class]]){
NSArray *deserializedArray = (NSArray *)jsonObject;
NSLog(#"Deserialized JSON Array = %#", deserializedArray);
}
else {
/* Some other object was returned. We don't know how to
deal with this situation as the deserializer only
returns dictionaries or arrays */
}
}
Hope it helps you!!
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
for (NSString *tempObject in json ) {
NSLog(#"Object: %#, Key: %#", [json objectForKey:tempObject], tempObject);
NSLog(#"Object: %#, Key: %#", [json valueForKey:tempObject], tempObject);
}
//OR by using fast enumeration
[json enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL *stop) {
NSLog(#"####Key Value is:%# = %#", key, object);
}];
Hope it helps you....!
Related
I have a NSURLConnection working that the return can be a dictionary or an array
How to know what is the kind of response Dictionary or array, so I do the appropriate serialisation?
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError* error;
NSDictionary* jsonDicto = [NSJSONSerialization
JSONObjectWithData:self.receivedData
options:kNilOptions
error:&error];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:self.receivedData
options:kNilOptions
error:&error];
}
Cheers .)
Use this:
id response = [NSJSONSerialization JSONObjectWithData:self.receivedData
options:kNilOptions
error:&error];
if([response isKindOfClass:[NSArray class]]) {
//Response is array
}
else if([response isKindOfClass:[NSDictionary class]]) {
//Reponse is Dictionary
}
I am getting a json array from the server. The jsonOutput object shows 2 objects correctly. But am unable to display or extract the data. Could some one help me out. I tried
the following way :
for (id key in jsonOutput) {
NSLog(#"key: %#, value: %#", key, [jsonOutput objectForKey:key]);
}
declaration :
NSDictionary *jsonOutput;
actualmethods :
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data=[[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
[data appendData:theData];
// if ([connection isEquals:connect1]){
// this is request urlConnectionRecsender
// }
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
jsonOutput= [NSJSONSerialization JSONObjectWithData:data options:nil error:nil];
for (id key in jsonOutput) {
NSLog(#"key: %#, value: %#", key, [jsonOutput objectForKey:key]);
}
}
Try this
NSError *error;
jsonOutput= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error)
NSLog(#"%#",error.description);
If you don't know what is response type, then it is always a good practice to check respone type first
id responseObj = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
if ([responseObj isKindOfClass:[NSArray class]]) {
//Your response is a array
}
else if([responseObj isKindOfClass:[NSDictionary class]]) {
//Your response is a dictionary
}
Your array contains NSDictionary
{ cropName = corn; cropOrderId = 1; cropPrice = 100; "farmer_id" = 1; orderStatus = pending; quantity = 5; }
use this code to get value
for(NSDictionary*dict in jsonObject) {
NSArray *allKeysarr = [dic allKeys];
for(NSString *key in allKeysarr) {
NSLog(#"%#",[dic valueForKey:key]);
}
}
first use error handling:
NSError *error;
jsonOutput= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error) NSLog(#"error: %#",error.description);
then access values with:
NSString *value1 = [jsonOutput objectForKey:#"YOUR_KEY1"];
NSData *xmlData = [NSData dataWithContentsOfFile:xmlPath];
NSError *jsonError = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:xmlData options:kNilOptions error:&jsonError];
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSLog(#"its an array!");
NSArray *jsonArray = (NSArray *)jsonObject;
NSLog(#"jsonArray - %#",jsonArray);
}
else {
NSLog(#"its probably a dictionary");
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
NSLog(#"jsonDictionary - %#",jsonDictionary);
}
Try this once
I have some NSData coming back from my server that is of type Json. I would like to know how to access the values present in the json and put them into there own NSString objects.
This is what the structure of the JsonArray looks like
This is the code I am using, however my for loop only ever shows "result" and nothing else.
NSError *error = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:csvData options: NSJSONReadingMutableContainers error: &error];
NSLog(#"%#", jsonArray);
if (!jsonArray) {
NSLog(#"Error parsing JSON: %#", error);
} else {
for(NSDictionary *item in jsonArray) {
NSLog(#"Item: %#", item);
}
}
You can access it like that:
for (NSDictionary *dict in jsonArray)
{
NSLog(#"Data: %#", dict[#"result"]);
}
You have dictionary in your array so you have to enumerate is and access it by key (result, etc.).
NSDictionary *resultDictionary = [jsonArray objectAtIndex: 0];
NSArray *resultArray = [resultDictionary objectForKey:#"result"];
for (NSString *item in resultArray)
{
NSLog (#"item: %#",item);
}
You should add some (non)sense checking.
u can access the json array like this,
for(NSDictionary *Mydictionary in MyJsonArray) {
Nsstring *DataOne = [Mydictionary objectforkey#"Mykey"];
}
For Cheking the json node u can put the json in this site and all the node will appear properly
http://json.parser.online.fr/
I am trying to get Dictionary form json, but the following code dosent seem to work. I am getting the JSON, but cannot get the dictionary from it.
NSString *str = [[NSMutableString alloc] initWithData:responseCust encoding:NSUTF8StringEncoding];
NSLog(#"CUSTOMER string -----################ %#", str);
if(str.length>5)
{
SBJSON *jsonparser=[[SBJSON alloc]init];
NSDictionary *res= [jsonparser objectWithString:str];
NSLog(#"Contants Results %#",res);
[jsonparser release];
[str release];
}
Thank You.
Please Follow the below code
NSURL * url=[NSURL URLWithString:str];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error;
//Get json data in Dictionary
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSLog(#"%#",json);
try this one..
Use NSJSONSerialization and make use of
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error to convert JSON to foundation object.
hope this helps
Just try to Either
NSDictionary *dict = [str JSONValue];
NSLog(#"%#", dict);
OR
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseCust options:nil error:&error];
NSLog(#"%#", dict);
+(NSDictionary *)converJsonStringToDictionary:(NSString *)jsonString
{
NSString *stringToConvert = jsonString;
if (![self isObjectEmpty:stringToConvert]) {
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *convertedData = nil;
convertedData = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (error != nil){
DLog(#"Error converting jsonString to dictionary: %#", [error description]);
convertedData = nil;
}
else if ([convertedData isKindOfClass:[NSDictionary class]]) {
DLog(#"The converted data is of kind NSDictionary");
}
else if ([convertedData isKindOfClass:[NSArray class]]){
DLog(#"The converted data is of kind NSArray");
convertedData = nil;
}
else{
DLog(#"The converted data is not NSDictionary/NSArray");
convertedData = nil;
}
return convertedData;
}
else{
DLog(#"The received jsonString is nil")
return nil;
}
}
Here, try adding the encoding...
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];
NSLog(#"dict: %#", jsonDict);
Check here for some samples on how to handle json on objective-c
Hi I have the following json that i need to parse, however, I'm struggling to parse the inner array. What I have currently just prints each of the inner arrays but I'd like to print say each title and add the titles to an array. Thank you for any help!
JSON
{"nodes":[{
"node":{
"nid":"1420857",
"title":"Title 1",
"votes":"182",
"popular":"True",
"teaser":"Teaser 1"
}},
{"node":{
"nid":"1186152",
"title":"Title 2",
"votes":"140",
"popular":"True",
"teaser":"Teaser 2"
}},
{"node":{
"nid":"299856",
"title":"Title 3",
"votes":"136",
"popular":"True",
"teaser":"Teaser 3"
}}
]}
Json Parser
NSError *error = nil;
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.somefilename.json"]];
if (jsonData) {
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (error) {
NSLog(#"error is %#", [error localizedDescription]);
return;
}
NSArray *keys = [jsonObjects allKeys];
for (NSString *key in keys) {
NSLog(#"%#", [jsonObjects objectForKey:key]);
}
} else {
// Handle Error
}
Just typecast it:
NSArray *nodes = (NSArray*)[jsonObjects objectForKey:#"nodes"];
for (NSDictionary *node in nodes){
// do stuff...
}
Methods that return id (like -[objectForKey:], and -[objectAtIndex:]) can return any objective-c object. You'll need to know ahead of time what to typecast it into to perform the appropriate operations on it. JSON is converted to the NSObject equivalents:
object -> NSDictionary
array -> NSArray
string -> NSString
number -> NSNumber
boolean -> NSNumber
float -> NSNumber
null -> NSNull
To differentiate between the various NSNumbers, you'll have to call the appropriate type method: -[intValue], -[boolValue], -[floatValue]. Check out the NSNumber docs for more info.
You can use my method for json parsing,
Parse Method:
-(void)jsonDeserialize:(NSString *)key fromDict:(id)content completionHandler:(void (^) (id parsedData, NSDictionary *fromDict))completionHandler{
if (key==nil && content ==nil) {
completionHandler(nil,nil);
}
if ([content isKindOfClass:[NSArray class]]) {
for (NSDictionary *obj in content) {
[self jsonDeserialize:key fromDict:obj completionHandler:completionHandler];
}
}
if ([content isKindOfClass:[NSDictionary class]]) {
id result = [content objectForKey:key];
if ([result isKindOfClass:[NSNull class]] || result == nil) {
NSDictionary *temp = (NSDictionary *)content;
NSArray *keys = [temp allKeys];
for (NSString *ikey in keys) {
[self jsonDeserialize:key fromDict:[content objectForKey:ikey] completionHandler:completionHandler];
}
}else{
completionHandler(result,content);
}
}
}
Method Call:
NSData *content = [NSData dataWithContentsOfFile:[[NSBundle mainBundle]pathForResource:#"Sample" ofType:#"json"]];
NSError *error;
//to get serialized json data...
id dictionary = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:&error];
//get data for key called GetInfo
[self jsonDeserialize:#"GetInfo" fromDict:dictionary completionHandler:^(id parsedData, NSDictionary *fromDict) {
NSLog(#"%# - %#",parsedData,fromDict);
}];