iOS 解析json串

时间:2023-01-21 22:52:18
NSString *json = @"[{\"name\":\"a1\",\"items\":[{\"x1\":\"item1\",\"x2\":\"item2\"}]},{\"name\":\"a2\",\"items\":[{\"x1\":\"item11\",\"x2\":\"item22\"}]}]" ;

    NSData *data = [json dataUsingEncoding:NSUTF8StringEncoding];

    NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

    for (NSMutableDictionary *row in dict) {
NSString *name = [row objectForKey:@"name"];
NSMutableArray *items = [row objectForKey:@"items"];
NSMutableDictionary *dict1 = items[];
NSLog(@"name=%@,x1=%@,x2=%@",name,[dict1 objectForKey:@"x1"],[dict1 objectForKey:@"x2"]); }

json格式:不说了,自己看,该字典就字典,该数组就数组。

[
{
"name": "a1",
"items": [
{
"x1": "item1",
"x2": "item2"
}
]
},
{
"name": "a2",
"items": [
{
"x1": "item11",
"x2": "item22"
}
]
}
]