1. 程式人生 > >IOS請求網路返回JSON解析

IOS請求網路返回JSON解析

-(NSDictionary*)Login:(NSString *)email password:(NSString *)password
  {
  NSMutableDictionary *resultsDictionary;// 返回的 JSON 資料
  NSDictionary *userDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:password, @"password",email,@"email",nil];
  if ([NSJSONSerialization isValidJSONObject:userDictionary])
  {

    NSError
*error; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userDictionary options:NSJSONWritingPrettyPrinted error: &error]; NSMutableData *tempJsonData = [NSMutableData dataWithData:jsonData]; NSURL *url = [NSURL URLWithString:@"http://seanchense.com/login"]; ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request addRequestHeader:@"Content-Type"
value:@"application/json; charset=utf-8"]; [request addRequestHeader:@"Accept" value:@"application/json"]; [request setRequestMethod:@"POST"]; [request setPostBody:tempJsonData]; [request startSynchronous]; NSError *error1 = [request error]; if (!error1) { NSString
*response = [request responseString]; NSLog(@"Test:%@",response); NSData* jsonData = [response dataUsingEncoding:NSUTF8StringEncoding]; } } return resultsDictionary; }

 //例項化一個書本管理類

        Book_manager *bm = [Book_manager new];

        //讀入檔案

        NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];

        //NSLog(@"%@",content);   //這句話可以用來測試是否讀取到資料

        //轉換成二進位制資料

        NSData * data = [content dataUsingEncoding:NSUTF8StringEncoding];

        //解析JSON檔案 OC中自帶的方法

        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

        //過濾節點,如果是{}就是詞典,如果是[]就是陣列,層層過濾

        dict = [dict objectForKey:@"root"];

        dict = [dict objectForKey:@"books"];

        NSArray * arr = [dict objectForKey:@"book"];

        //遍歷陣列並新增進書本管理

        for (NSDictionary * dd in arr) {

    //例項化一本書

            BOOK *book = [BOOK new];

            book.Id = [dd objectForKey:@"-id"];

            book.language = [dd objectForKey:@"-language"];

            book.name = [dd objectForKey:@"name"];

            book.price = [[dd objectForKey:@"price"] doubleValue];

            book.auther_name = [[dd objectForKey:@"auther"] objectForKey:@"name"];

            book.summary = [dd objectForKey:@"summary"];

    //新增書本進管理類中

            [bm addBOOK:book];

        }

參考:https://segmentfault.com/a/1190000000519598,https://www.cnblogs.com/dengsir/articles/5162216.html