【发布时间】:2015-03-07 16:25:54
【问题描述】:
我从 NSURLRequest 中得到一个字符串。然后我反序列化字符串以将其转换为 NSDictionary,如下所示:
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(responseString && responseString.length) {
NSLog(@"%@", responseString);
NSError *jsonError;
NSData *objectData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
NSLog(@"STRING DESERIALIZADA=%@",json);
我得到以下 json NSDictionary 的结果:
{
meta = {
limit = 20;
next = "<null>";
offset = 0;
previous = "<null>";
"total_count" = 1;
};
objects = (
{
color = Plata;
"current_latitude" = "-12.19061989";
"current_longitude" = "-77.004078";
employee = {
active = 1;
dni = 78965412;
id = 2;
lastname = volongo;
mail = "rv@alosda.pe";
name = Ronaldo;
phone = 12355688;
photo = "http://example_url/media/employee/default.png";
"resource_uri" = "/rest/employee/2/";
};
id = 1;
"license_plate" = 2752727;
model = Toyota;
"property_card" = "AAA-XXX";
"resource_uri" = "/rest/clientaxiradio/1/";
state = 0;
year = 2014;
}
);
}
这一次,“objects”键下的结果包括1个对象,但以后结果响应中的对象会更多。
我需要知道的是在这种情况下(只有 1 个对象)以及响应包含多个对象时如何检索每个对象键的值。
谢谢。
【问题讨论】:
-
我对你的最后一句话有点困惑。您是在问如何从
object中检索所有objects,或者如何从字典中检索多个object(及其子项)? -
@l'L'l,对不起我的英语,我的意思是,例如,如何从现在在 NSDictionary 中的唯一对象中检索 current_location 的值,以及稍后,当字典可能有多个对象,如何从所有对象中检索 current_latitude 的值。
-
你可以将对象保存在 NSArray.. 并且 NSArray 数组将是字典数组
-
假设你的完整数据在 NSDictionary json for Object 你可以写 NSArray * objects=[json objectForKey:@"objects"];该数组将包含对象中的所有字典此外,您现在可以使用对象数组解析 json
-
@Rajan,谢谢,我会试试的。
标签: ios json nsdictionary