How to use NSJSONSerialization

后端 未结 12 755
天涯浪人
天涯浪人 2020-11-22 08:38

I have a JSON string (from PHP\'s json_encode() that looks like this:

[{\"id\": \"1\", \"name\":\"Aaa\"}, {\"id\": \"2\", \"name\":\"Bbb\"}]
         


        
12条回答
  •  天涯浪人
    2020-11-22 09:20

    The following code fetches a JSON object from a webserver, and parses it to an NSDictionary. I have used the openweathermap API that returns a simple JSON response for this example. For keeping it simple, this code uses synchronous requests.

       NSString *urlString   = @"http://api.openweathermap.org/data/2.5/weather?q=London,uk"; // The Openweathermap JSON responder
       NSURL *url            = [[NSURL alloc]initWithString:urlString];
       NSURLRequest *request = [NSURLRequest requestWithURL:url];
       NSURLResponse *response;
       NSData *GETReply      = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
       NSDictionary *res     = [NSJSONSerialization JSONObjectWithData:GETReply options:NSJSONReadingMutableLeaves|| NSJSONReadingMutableContainers error:nil];
       Nslog(@"%@",res);
    

提交回复
热议问题