我将JSON作为NSString:
[{"bus_number":"1","created_at":"2011-08-15T23:07:52Z","id":1,"model":"Setra","registar_number":"123456","seats":50,"tour_id":1,"updated_at":"2011-08-15T23:07:52Z"},{"bus_number":"2","created_at":"2011-08-15T23:07:52Z","id":2,"model":"Mercedes","registar_number":"2234","seats":60,"tour_id":1,"updated_at":"2011-08-15T23:07:52Z"}]
我正在尝试将此NSString转换为NSDictionary。
当我使用时:
NSDictionary *sourceDictionary = [[response bodyAsString] objectFromJSONString];
我得到像这样的NSDictionary:
(
{
"bus_number" = 1;
"created_at" = "2011-08-15T23:07:52Z";
id = 1;
model = Setra;
"registar_number" = 123456;
seats = 50;
"tour_id" = 1;
"updated_at" = "2011-08-15T23:07:52Z";
},
{
"bus_number" = 2;
"created_at" = "2011-08-15T23:07:52Z";
id = 2;
model = Mercedes;
"registar_number" = 2234;
seats = 60;
"tour_id" = 1;
"updated_at" = "2011-08-15T23:07:52Z";
}
)
但是,这个NSDictionary有一个问题,我无法访问他们的元素,有些元素不是NSStrings(就像模型一样)。
如何使用NSStrings将JSONString转换为NSDictionary?
修改
当我尝试使用以下命令登录控制台时:
for (id key in sourceDictionary) {
NSLog(@"key: %@, value: %@", key, [sourceDictionary objectForKey:key]);
}
我得到例外:
-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x1c3a50
答案 0 :(得分:2)
如果你是从RestKit那里得到的,看起来就像你一样,你可以这样做:
NSMutableDictionary *myDictionary = [response.body mutableObjectFromJSONData];
通过这种方式,您可以将二进制数据拉入原始状态,并且可以避免在流程中来回转换为字符串的不必要(且代价高昂)。此外,我规定了可变性,因为当你得到数据时,你很可能想要操纵或捣乱数据......再次,来自JSONKit超类的非可变对象和可变对象之间的转换涉及成本......所以从一开始就加入变数,你就节省了一些时间。
答案 1 :(得分:1)
这些实际上是NSStrings,当你把它们打印到控制台时它们只是没有引号。