使用 NSJSONSerialization 的 JSON 解析目標 c

NSError *e = nil;
NSString *jsonString = @"[{\"id\": \"1\", \"name\":\"sam\"}]";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

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);
    }
}

輸出:

Item: {
    id = 1;
    name = sam;
}

示例 2:使用 url 的內容:

//Parsing:

NSData *data = [NSData dataWithContentsOfURL:@`URL HERE`];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@“json :%@”,json);

樣品回覆:

json: {
    MESSAGE = “Test Message";
    RESPONSE =(
                {
            email = "test@gmail.com";
            id = 15;
            phone = 1234567890;
            name = Staffy;
        }
    );
    STATUS = SUCCESS;
}

 NSMutableDictionary *response = [[[json valueForKey:@"RESPONSE"] objectAtIndex:0]mutableCopy];
 NSString *nameStr = [response valueForKey:@"name"];
 NSString *emailIdStr = [response valueForKey:@"email"];