我正在尝试使用字典形式json,但以下代码似乎有效。我正在获取JSON,但无法从中获取字典。
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];
}
谢谢。
答案 0 :(得分:2)
请按照以下代码
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);
尝试这个..
答案 1 :(得分:1)
使用NSJSONSerialization并使用
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error to convert JSON to foundation object.
希望这会有所帮助
答案 2 :(得分:0)
尝试
NSDictionary *dict = [str JSONValue];
NSLog(@"%@", dict);
或强>
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseCust options:nil error:&error];
NSLog(@"%@", dict);
答案 3 :(得分:0)
+(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;
}
}
答案 4 :(得分:0)
在这里,尝试添加编码...
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];
NSLog(@"dict: %@", jsonDict);