2013年10月29日 星期二

網址可以直接get到json時的做法

NSURL* url = [NSURL URLWithString:@"http://www.marq.com.tw/ooxx"];
   
    //這個方法會卡住main thread造成不順,但這裡的json大小只有幾byte,所以剛好可以適用。
    NSData *jsonData = [NSData dataWithContentsOfURL:url];

    NSString *myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"data = %@",myString);
   
    NSError* error = nil;
    if (jsonData) {
        id _jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData                                                 options:NSJSONReadingMutableContainers error:&error];
        if ([_jsonObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary* jsonDictionary = (NSDictionary*)_jsonObject;
            NSLog(@"%@",jsonDictionary);
        }else if ([_jsonObject isKindOfClass:[NSMutableArray class]]) {
            NSArray* jsonArray = (NSArray*)_jsonObject;
            NSLog(@"%@",jsonArray);
        }
    }

沒有留言:

張貼留言