【问题标题】:Convert JSON feed to NSDictionary将 JSON 提要转换为 NSDictionary
【发布时间】:2011-06-29 15:08:20
【问题描述】:

JSON_CATEGORY_DATA_URL_STRING 是我的提要 URL,它返回如下:

[
    {
        "group":"For Sale",
        "code":"SSSS"
    },
    {
        "group":"For Sale",
        "category":"Wanted",
        "code":"SWNT"
    }
]

我似乎无法从以下代码中得到一个不错的NSDictionary(或NSArray):

+ (NSDictionary *)downloadJSON
{

NSDictionary *json_string;
NSString *dataURL = [NSString stringWithFormat:@"%@", JSON_CATEGORY_DATA_URL_STRING];
NSLog(@"%@",dataURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];    
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease];
NSDictionary *json_dict = (NSDictionary *)json_string;
NSLog(@"json_dict\n%@",json_dict);
    NSLog(@"json_string\n%@",json_string);

return json_string;
}

我已经阅读了很多关于此的帖子,但没有得到它。

【问题讨论】:

  • FWIW,JSONValue 只返回 null?
  • 嗯......原来这是一个糟糕的提要。原始代码很好(甚至在重写 6 次并在此处发布之前)。

标签: ios objective-c nsarray nsdictionary sbjson


【解决方案1】:

您不能只将字符串转换为字典并期望它解析 JSON。您必须使用 JSON 解析库来获取该字符串并将其转换为字典。

【讨论】:

【解决方案2】:

您需要使用 JSON 解析器。这是修改后的代码

+ (NSDictionary *)downloadJSON
{

NSDictionary *json_string;
NSString *dataURL = [NSString stringWithFormat:@"%@", JSON_CATEGORY_DATA_URL_STRING];
NSLog(@"%@",dataURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];    
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease];
//JSONValue is a function that will return the appropriate object like dictionary or array depending on your json string.
NSDictionary *json_dict = [json_string JSONValue];
NSLog(@"json_dict\n%@",json_dict);
    NSLog(@"json_string\n%@",json_string);

return json_dict;
}

这应该是获取 NSDictionary 的代码。但是您的 json 字符串是一个数组,因此请改用 .

+ (NSArray *)downloadJSON
{

NSDictionary *json_string;
NSString *dataURL = [NSString stringWithFormat:@"%@", JSON_CATEGORY_DATA_URL_STRING];
NSLog(@"%@",dataURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:dataURL]];    
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

json_string = [[[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]autorelease];
NSArray *json_dict = [json_string JSONValue];
NSLog(@"json_dict\n%@",json_dict);
    NSLog(@"json_string\n%@",json_string);

return json_dict;
}

编辑: 您需要使用 JSON.framework 调用 JSONValue 方法。
您还需要返回json_dict 而不是json_string,因为json_stringNSString 类型而不是NSDictionaryNSArray
并且不要自动释放它,因为它是你的类变量

【讨论】:

  • 即使作为 NSArray 我仍然得到 json_dict 空值。此外,警告“NSArray(或 NSDict)可能无法响应 JSONValue”
  • 您是否在头文件中导入了JSON parser
  • 是的,我知道你做错了什么,看看我编辑的答案。
  • 指出明显的,json_string被声明为NSDictionary *,但是你说json_string是NSString类型的。
【解决方案3】:

使用 IOS5,您可以使用 NSJSONSerialization 序列化 JSON。

NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

【讨论】:

  • NSJSONWritingPrettyPrinted 是 writeJSONObject: 中使用的写入选项,如果您在此上下文中使用它,您将获得 NSJSONReadingMutableContainers 应用于读取的效果。
  • 我使用了相同的NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&writeError]; // NSString *strJsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSDictionary *dicJsonRequest = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&convertError];它成功转换字符串但对于字典它没有转换为json格式
  • 错误也是空的。这行有什么问题。我已经复制粘贴了你的代码
  • 确定您的 JSON 是按照标准编写的?
【解决方案4】:

我创建了一个类来简化这项任务。它使用 iOS 5 的 NSJSONSerialization。从 github here 克隆它。

【讨论】:

    【解决方案5】:

    创建获取json数据的方法。在urlwithstring中传递你的url。

    -(void)fetchjsondata
    {
         NSString *login= [[NSString stringWithFormat:@"your url string"]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
        NSLog(@"----%@", login);
        NSURL *url = [NSURL URLWithString:[login stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        //-- Get request and response though URL
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
    
    
        [NSURLConnection sendAsynchronousRequest:request
                                           queue:[NSOperationQueue mainQueue]
                               completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                                   dispatch_async(dispatch_get_main_queue(), ^{
                                       if (data) {
                                           dic_property= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                                           NSLog(@"%@", dic_property);
                                           NSLog(@"counts=%d",[[dic_property objectForKey:@"Data"]count]);
    
    
    
                                       }
                                       else {
                                           NSLog(@"network error, %@", [error localizedFailureReason]);
                                       }
                                   });
    
                               }];
    
    }
    

    在任何地方调用 fetchjsonmethod。

    [NSThread detachNewThreadSelector:@selector(fetchdata) toTarget:self withObject:nil];

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-15
      • 1970-01-01
      • 1970-01-01
      • 2017-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多