如何从以下JSON
获取值。
JSON
{
"X": [
{
"one": 1,
"two": "Bill"
},
{
"one": 2,
"two": "Hutch"
}
]
}
代码
NSDictionary *dictionary = (NSDictionary *) responseObject;
dc =[dictionary objectForKey:@"X"];
现在我如何打印" one"和"两个"
注意:dc
是NSMutableDictionary
。
答案 0 :(得分:1)
使用此代码..
NSString *str = @"{\"X\":[{\"one\": 1, \"two\": \"Bill\" }, { \"one\": 2, \"two\": \"Hutch\" } ] }";
str = @"{\"X\":[{\"one\": 1,},{\"one\": 2,\"two\": \"Hutch\"}]}";
NSError *jsonError;
NSData *objectData = [str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
NSLog(@"%@",[json objectForKey:@"X"]);
NSMutableDictionary *dict = [json objectForKey:@"X"];
for (NSDictionary *tempDict in dict) {
NSLog(@"%@",tempDict);
if ([tempDict objectForKey:@"one"]) {
NSLog(@"%@",[tempDict objectForKey:@"one"]);
}
if ([tempDict objectForKey:@"two"]){
NSLog(@"%@",[tempDict objectForKey:@"two"]);
}
}
希望这可以帮到你:)
答案 1 :(得分:0)
看这里是你的JSON
{ " X":[ { "一个":1, "两个":"比尔" }, { "一个":2 , "两个":" Hutch" } ]}
要从X数组中获取第二个对象,并在&#34中获得第二个对象;一个" :
NSString *value = [[[dictionary objectForKey:@"X"] objectAtIndex: 1] objectForKey: @"one"];
以下是单行中使用的相同代码的多行说明:
NSArray *arr = [dictionary objectForKey:<Root Key String>]; // save data to array from dictionary
NSDictionary *dict = [arr objectAtIndex: <Index of object>]; // get the actual object from array based on index
NSString *resultString = [dict objectForKey: <Key String>]; // get value of your required key