iOS NSURLConnection dictionary or array - ios

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
}

Related

i Can't convert NSData to NSMutableArray

I want to try to convert NSData to NSDictionary or NSArray but some how i can't do that but whenever try to convert into NSString it will converted and gating data so any one can know what is mistake ,help me below is code for convert
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
Below code for convert into NSString
NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
But Problem is that When get this type of data it will converted on array
Response:
[["superwoman",0],["sugar",0],["sultan trailer",0],["summer",0],["superman",0],["sunday candy",0],["sublime",0],["summer sixteen",0],["superfruit",0],["sultan songs",0]]
but Whenever gat this type of response it will not converted on array formated because of ,[3 on response
Response:
[["ssundee",0],["selena gomez",0],["sia",0],["sorry beyonce",0],["smosh",0],["sweatshirt jacob
sartorius",0],["skydoesminecraft",0],["secret life of pets
trailer",0,[3]]
try this one
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseObject
options:kNilOptions
error:&error];
1)You need to take the response in id type variable & check the class of response like below.
2)You also need to check if JSON convertion is successful
NSError * error;
id result = [NSJSONSerialization JSONObjectWithData:data
options:0 error:&error];
if (!error) {
if([id isKindOfClass:[NSDictionary class]]){
//Response is Dictonary
} else if ([id isKindOfClass:[NSArray class]]){
//Response is Array
} else {
//any other format
}
} else {
//Handle error
}

Convert JSON array to Objective-C in iOS

I am new to iOS development. I am trying to covert JSOn array values to Objective-C values. My JSON values are like this:
{"result":
[{"alternative":
[{"transcript":"4"},
{"transcript":"four"},
{"transcript":"so"},
{"transcript":"who"}],
"final":true}],
"result_index":0}
I have tried it this way:
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:speechrequestString]];
NSError *error;
NSDictionary *speechResult= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *speechArray= [speechResult valueForKey:#"result"];
NSLog(#"%#",speechArray);
NSLog(#"Response is of type: %#", [speechArray class]);
speechArray is always null. How to resolvee this problem?
At the same time I would like to print transcript values.
I think the problem might be in initializing the array and Dictionary.
Try doing this,
NSDictionary *speechResult = [NSDictionary new];
NSArray *speechArray = [NSArray new];
Hope it helps..
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];//data is your response from server as NSData
if ([json isKindOfClass:[NSDictionary class]]){ //Added instrospection as suggested in comment.
NSArray * speechArray = json[#"result"];
}
NSLog(#"speech array %#",speechArray);
Did you check the value in NSDictionary (speechResult).
If it is nil, check the json data isValid or not.
NSError *error;
if ([NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error] == nil)
{
// Check the error here
}else {
// here check whether it is a dictionary and it has key like #Bhadresh Mulsaniya mentioned.
}
If returns nil, then you check the error to understand what's wrong.
try this may be it will help you:-
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:speechrequestString]];
NSError *error;
NSDictionary *speechResult = [NSDictionary new];
speechResult= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *speechArray = [[NSArray alloc]init];
speechArray= [speechResult valueForKey:#"result"];
NSLog(#"%#",speechArray);
NSLog(#"Response is of type: %#", [speechArray class]);
try this code,
restaurantdictionary = [NSJSONSerialization JSONObjectWithData:mutableData options:NSJSONReadingMutableContainers error:&e];
NSMutableArray *main_array=[[NSMutableArray alloc]init];
main_array=[restaurantdictionary valueForKey:#"results"];
NSLog(#"main_array %#", main_array);
its working for me, hope its helpful
You have to initialize the array before using it,
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:speechrequestString]];
NSError *error;
NSDictionary *speechResult= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *speechArray= [[NSArray alloc] init];
speechArray= [speechResult valueForKey:#"result"];
if (speechArray.count>0) {
NSDictionary * alternativeDictn = [speechArray objectAtIndex:0];
NSArray *alternativeAry= [[NSArray alloc] init];
alternativeAry = [alternativeDictn objectForKey:#"alternative"];
NSLog(#"%#",alternativeAry);
}
NSLog(#"Response is of type: %#", [speechArray class]);
Using this code you will get following result,
(
{
transcript = 4;
},
{
transcript = four;
},
{
transcript = so;
},
{
transcript = who;
}
)
Try out the below code to get the transcripts:
NSData* jsonData = [yourJsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *responseObj = [NSJSONSerialization
JSONObjectWithData:jsonData
options:0
error:&error];
if(! error) {
NSArray *responseArray = [responseObj objectForKey:#"result"];
for (NSDictionary *alternative in responseArray) {
NSArray *altArray = [alternative objectForKey:#"alternative"];
for (NSDictionary *transcript in altArray) {
NSLog(#"transcript : %#",[transcript objectForKey:#"transcript"]);
}
}
} else {
NSLog(#"Error in parsing JSON");
}
You should alloc your dictionary first like this-
NSDictionary *speechResult = [[NSDictionary alloc]init];
speechResult= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *speechArray = [[NSArray alloc]init];
speechArray= [speechResult valueForKey:#"result"];

Objective C iterate over and NSDictionary within an NSDictionary

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....!

Unable to read data after NSJSONSerialization

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

Getting Dictionary From JSON

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

Resources