ios 将 JSON 提要转换为 NSDictionary

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5038371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:55:42  来源:igfitidea点击:

Convert JSON feed to NSDictionary

iosobjective-cnsarraynsdictionarysbjson

提问by linkingarts

Where JSON_CATEGORY_DATA_URL_STRINGis my feed URL, which returns fine as:

哪里JSON_CATEGORY_DATA_URL_STRING是我的供稿网址,它返回细如:

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

I cannot seem to get a nice NSDictionary(or NSArray) out of the following code:

我似乎无法从以下代码中得到一个好的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;
}

I've read many posts on this, but am not getting it.

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

回答by lagos

With IOS5 you can use NSJSONSerializationfor serializing the JSON.

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

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

回答by Carl Veazey

You can't just cast a string as a dictionary and expect it to parse the JSON. You must use a JSON parsing library to take that string and convert it into a dictionary.

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

回答by OscarVGG

I made a class that makes this task easier. It uses iOS 5's NSJSONSerialization. Clone it from github here.

我做了一个类,使这个任务更容易。它使用 iOS 5 的 NSJSONSerialization。从这里从 github 克隆它。

回答by Robin

You need to use JSON parser. here is the edited code

您需要使用 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;
}

this should be the code to get the NSDictionary. but you json string is an array so instead use .

这应该是获取 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;
}

Edit: you need to use JSON.framework to call JSONValue method.
also you need to return json_dictinstead of json_stringas json_stringis of NSStringtype and not NSDictionaryor NSArray.
and dont autorelease it, as it is your class variable

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

回答by Jigar Darji

create method to fetchjson data.Pass your url in urlwithstring.

创建 fetchjson 数据的方法。在 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]);
                                   }
                               });

                           }];

}

call fetchjsonmethod in anywhere.

在任何地方调用 fetchjsonmethod。

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

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