How to use NSJSONSerialization

后端 未结 12 738
天涯浪人
天涯浪人 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:02

    Your root json object is not a dictionary but an array:

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

    This might give you a clear picture of how to handle it:

    NSError *e = nil;
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
    
    if (!jsonArray) {
      NSLog(@"Error parsing JSON: %@", e);
    } else {
       for(NSDictionary *item in jsonArray) {
          NSLog(@"Item: %@", item);
       }
    }
    

提交回复
热议问题