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
Related
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"];
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.
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.
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 am getting back some data from an API and the data is a string.
po JSON
$22 = 0x26305840 {
"thing_id" = 5192f9053000001;
status = "{\"thing_request_id\":\"51c3a0608906f101f\",\"thing_id\":\"5192f9053000001\",\"status\":\"PICKUP\"}";
}
How can I access the inner status key? NOT the "stat =" one.
I am getting access to the data via a socketIO connection.
What you are looking for is NSJSONSerialization.
you can use it like:
NSData *data = [stringJSON dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
id *yourJSON = [JSONObjectWithData:webData options:0 error:&error];
if(error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"You JSON: %#", yourJSON);
}
It is important to observe that it can return an array or a dictionary, this code is only an example.
Documentation:
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html
This code work well for fixing JSON with unquoted key. I got it from https://coderwall.com/p/tdra3w
- (NSString *)fixJSON:(NSString *)s {
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:#"[{,]\\s*(\\w+)\\s*:"
options:0
error:NULL];
NSMutableString *b = [NSMutableString stringWithCapacity:([s length] * 1.1)];
__block NSUInteger offset = 0;
[regexp enumerateMatchesInString:s
options:0
range:NSMakeRange(0, [s length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSRange r = [result rangeAtIndex:1];
[b appendString:[s substringWithRange:NSMakeRange(offset, r.location - offset)]];
[b appendString:#"\""];
[b appendString:[s substringWithRange:r]];
[b appendString:#"\""];
offset = r.location + r.length;
}];
[b appendString:[s substringWithRange:NSMakeRange(offset, [s length] - offset)]];
return b;
}
I would suggest adding JSONKit which will make it simple to put it in a dictionary and access each element.
NSData *jsonData = [yourJSONString dataUsingEncoding:NSUTF8String];
NSDictionary *dictionary = [jsonData objectFromJSONData];
Then you can access each element the same as you would a normal NSDictionary.
[dictionary objectForKey:#"status"];//etc
You can get JSONKit here
Not efficient code but I just simply call it twice and it works.
NSError *jsonParsingError = nil;
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData: [packet.args[0] dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &jsonParsingError];
NSString *lastStatus = [JSON objectForKey:#"status"];
NSDictionary *lastStatusDict = [JSON objectForKey:#"status"];
NSError *jsonParsingError = nil;
NSDictionary *INNERJSON =
[NSJSONSerialization JSONObjectWithData: [lastStatus dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &jsonParsingError];
NSString *innerStatus = [INNERJSON objectForKey:#"status"];
THEN I CAN USE IT
if ([innerStatus isEqualToString:kSENT]) { .....