iOS Error Parsing JSON - ios

I am new to iOS. I have this JSON data that I needed to parse:
{
"allseries":[
{
"type":"HR",
"title":"Heart Rate",
"xLabel":"Time",
"yLabel":"Beats per Min",
"defaultUnit":"BPM",
"url":"info/info?user=admin%40korrent.com&type=HR",
"size":18,
"firstTs":1406755651,
"lastTs":1406841254
},
{
"type":"TEMP",
"title":"Temperature",
"xLabel":"Time",
"yLabel":"Temperature",
"defaultUnit":"F",
"url":"info/info?user=admin%40korrent.com&type=TEMP",
"size":6,
"firstTs":1406854147,
"lastTs":1406854283
}
],
"status":"OK"
}
So far this is my code:
NSString *dataReceived= [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
NSLog(#"--> async response data (string): %#", dataReceived);
NSData *jsonData = [dataReceived dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&jsonError];
NSLog(#"JSON key and value %#", [dict description]);
NSLog(#" %# ", dict[#"allseries"]);
NSString *jsonString=dict[#"allseries"];
if (_programState == 4){
NSLog(#"state is 4");
NSLog(#"%#",jsonString);
NSData *Data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
However, the code throws invalid argument exception for this line:
NSData *Data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
Further more, jsonString seems totally "inoperable". I cannot split it, append strings to it etc. So what's wrong?

// The following two lines are just for logging and otherwise are not needed.
NSString *dataReceived= [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
NSLog(#"--> async response data (string): %#", dataReceived);
// Deserialize the JSON data into a dictionary
NSError *jsonError;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData: _responseData options:nil error:&jsonError];
NSLog(#"JSON key and value %#", dict);
// Get the array from the dictionary element "allseries".
NSArray *jsonArray = dict[#"allseries"];
NSLog(#"jsonArray: %#", jsonArray);
Here jsonArray is the array of dictionaries for "allseries" from the JSON

What you did is totally, totally wrong.
dict[#allseries] is not an NSString. It is an NSArray with two elements, and both its elements are NSDictionary.

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
}

How to get value from NSArray ios

I have got json response like following
Photo = ["\image1.jpg\","\image2.jpg\","\image3.jpg\"]
How can i get only name from this json response.
I want output like
Image1.jpg
Image2.jpg
Image3.jpg
Without [] and "".
First of all, Your Photo String is not in proper format. The correct String is as follows:
NSString *jsonString = #"[\"\image1.jpg\",\"\image2.jpg\",\"\image3.jpg\"]";
Try out the below code to get image name from Your String:
NSString *jsonString = #"[\"\image1.jpg\",\"\image2.jpg\",\"\image3.jpg\"]";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e = nil;
NSArray *json = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
if (!json) {
NSLog(#"Error parsing JSON: %#", e);
} else {
NSLog(#"Item: %#", json);
for(NSString *item in json) {
NSLog(#"Item: %#", item);
}
}

Null JSON response

NSString *connection = #"http:"(link);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
NSURL *url = [NSURL URLWithString:connection];
NSString *json = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
NSLog(#"\nJSON: %# \n Error: %#", json, error);
if(!error) {
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%#",jsonData);
NSMutableArray *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
NSLog(#"JSON: %#", jsonDict);
}
});
The above code returns :
JSON: "{\"value\":[{\"Id\":\" }}
but
NSData is 69746963 735c222c 5c224973 41767469 76655c22 3a5c2231 5c222c
and jsonDict returns (null).
I am confused what may be going on.
Can somebody please help me figure it out.
I am trying to get the JSON data but it returns null.
Thanks
You say the server gave you this:
JSON: "{\"value\":[{\"Id\":\" }}
If I remove the backslashes that were added by the NSLog command, the actual JSON that you received was
{"value":[{"Id":" }}
That isn't valid JSON. That's all there is to it; the server sent you rubbish data, and there is no way to get any information from it. Contact the people creating the server software and ask them to fix the problem.
And you really, really need to distinguish between what an object really contains, and what NSLog prints. NSLog prints the contents of an NSData object by displaying each byte as two hexadecimal digits.
Try one of these (array or dictionary) without converting it into JSON, depending on what u want :
NSString *connection = #"http://(link)";
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSDictionary *jsonDict = [NSDictionary dictionaryWithContentsOfURL:[NSURL URLWithString:connection]];
NSArray *jsonArray = [NSArray arrayWithContentsOfURL:[NSURL URLWithString:connection]];
NSLog(#"DICT: %# ARRAY: %#", jsonDict, jsonArray);
});
I haven't tried it, please paste results?
By the look of your NSString response, it starts with { and ends with } which means it is a NSDictionary.
Change :
NSMutableArray *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
to :
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&error];

iOS is creating a JSON String without {} -- only has [ ]?

Why is the assignment to jsonString not including braces{}?
Here's what I'm getting:
["anemail#chdr.com"]
CODE
if (_allEmails)
{
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:_allEmails options:0 error:&error];
if (!error)
{
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[dictionary setObject:jsonString forKey:#"AllEmails"];
}
}
The _allEmails variable must be an array (you tell me) and for braces you need to store your data in a dictionary.
Perhaps what you're looking for is:
if ([_allEmails count] > 0)
{
NSError *error = nil;
NSDictionary *dict = #{ #"AllEmails" : _allEmails };
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:0
error:&error];
// Note: Check returned object and not NSError object
if (jsonData) {
NSString *jsonString = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
// Do thing with string
} else {
NSLog(#"Failed to serialize JSON: %#", [error localizedDescription]);
}
}
Because a JSON array is not enclosed braces, and what you have above is a JSON array. A JSON "object" is enclosed in braces.

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