Ответ 1
С IOS5 вы можете использовать NSJSONSerialization для сериализации JSON.
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
Где 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;
}
Я читал много сообщений об этом, но не понимаю.
С IOS5 вы можете использовать NSJSONSerialization для сериализации JSON.
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
Вы не можете просто ввести строку в качестве словаря и ожидать, что она будет анализировать JSON. Вы должны использовать библиотеку разбора JSON, чтобы взять эту строку и преобразовать ее в словарь.
Я создал класс, облегчающий эту задачу. Он использует iOS 5 NSJSONSerialization. Клонировать его из github здесь.
Вам нужно использовать парсер 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 string - это массив, поэтому вместо этого используйте.
+ (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_string
имеет тип NSString
, а не NSDictionary
или NSArray
.
и не autorelease это, так как это ваша переменная класса
создайте метод для данных fetchjson. Проведите свой URL-адрес в urlwithstring.
-(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];