0

我正在尝试获取字典形式的 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];
}

谢谢你。

4

5 回答 5

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);

试试这个。。

于 2013-09-05T12:28:29.527 回答
1

使用NSJSONSerialization并利用

+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error to convert JSON to foundation object.

希望这可以帮助

于 2013-09-05T12:26:06.267 回答
0

在这里,尝试添加编码...

NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];

NSLog(@"dict: %@", jsonDict);

在此处查看有关如何在 Objective-c 上处理 json 的一些示例

于 2013-09-05T12:40:33.657 回答
0

只是尝试 要么

NSDictionary *dict = [str JSONValue];
NSLog(@"%@", dict);

或者

NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseCust options:nil error:&error];
NSLog(@"%@", dict);
于 2013-09-05T12:22:07.663 回答
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;
    }
}
于 2013-09-05T12:31:42.827 回答