How to use NSJSONSerialization

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

    This is my code for checking if the received json is an array or dictionary:

    NSError *jsonError = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&jsonError];
    
    if ([jsonObject isKindOfClass:[NSArray class]]) {
        NSLog(@"its an array!");
        NSArray *jsonArray = (NSArray *)jsonObject;
        NSLog(@"jsonArray - %@",jsonArray);
    }
    else {
        NSLog(@"its probably a dictionary");
        NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
        NSLog(@"jsonDictionary - %@",jsonDictionary);
    }
    

    I have tried this for options:kNilOptions and NSJSONReadingMutableContainers and works correctly for both.

    Obviously, the actual code cannot be this way where I create the NSArray or NSDictionary pointer within the if-else block.

提交回复
热议问题