I'm in trouble with parsing JSON. The characters of outputs are garbled.

Please tell me to how to solve this problem. What become the problem is the next point.

NSLog(@"Dictionary '%@'",dictionary); // ◀︎ here
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *urlString=[NSString stringWithFormat:@"http://webservice.recruit.co.jp/hotpepper/gourmet/v1/?key=4f46fcd28f4b15e3&lat=34.678&lng=135.52&range=5&order=4&format=json"];
NSString *urlUTF8=[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:urlUTF8];

NSString *jsonString=[self performServerRequestWithURL:url];


NSDictionary *dictionary=[self parseJSON:jsonString];
NSLog(@"Dictionary '%@'",dictionary); // ◀︎ here

}

-(NSString*)performServerRequestWithURL:(NSURL*)url
{
NSError *error;
NSString *resultString=[NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];

if(resultString == nil){
    NSLog(@"ダウンドード失敗:%@",error);
    return nil;
}
return resultString;
}

-(NSDictionary*)parseJSON:(NSString*)jsonString
{
NSData *data=[jsonString dataUsingEncoding:NSUTF8StringEncoding];

NSError *error;
id resultObject=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];


if([resultObject isKindOfClass:[NSDictionary class]]){
    NSLog(@"its an dictionary");
    NSDictionary *jsonDictionary=(NSDictionary*)resultObject;

} else {
    NSLog(@"its probably a array");
    NSArray *jsonArray=(NSArray*)resultObject;
        }



return resultObject;
}
有帮助吗?

解决方案

YOur code is perfect you just have to return dictionary in stead of resultobject as @iPatel said.

Replace this code in your code..

-(NSDictionary*)parseJSON:(NSString*)jsonString
{
    NSData *data=[jsonString dataUsingEncoding:NSUTF8StringEncoding];

    NSError *error;
    id resultObject=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

    NSDictionary *jsonDictionary;
    if([resultObject isKindOfClass:[NSDictionary class]]){
        NSLog(@"its an dictionary");
        jsonDictionary=(NSDictionary*)resultObject;
        NSLog(@"jsonDictionary : %@",jsonDictionary);

    } else {
        NSLog(@"its probably a array");
        NSArray *jsonArray=(NSArray*)resultObject;
        NSLog(@"jsonArray : %@",jsonArray);
    }
    return jsonDictionary;
}

But your code contain NSArray also does that means json can be either array or dictionary than you have to change your return type to id so you can return any item.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top