How to use NSJSONSerialization

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

    It works for me. Your data object is probably nil and, as rckoenes noted, the root object should be a (mutable) array. See this code:

    NSString *jsonString = @"[{\"id\": \"1\", \"name\":\"Aaa\"}, {\"id\": \"2\", \"name\":\"Bbb\"}]";
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *e = nil;
    NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&e];
    NSLog(@"%@", json);
    

    (I had to escape the quotes in the JSON string with backslashes.)

提交回复
热议问题