json的介绍和格式参看 http://blog.csdn.net/totogogo/article/details/3766163
iOS 5之前是使用open source lib: JSONKit (https://github.com/johnezang/JSONKit)
iOS 5提供了NSJSONSerialization。
NSJSONSerialization最常用的几个方法
把NSData json object转换成Foundation json object,返回值Foundation json object的type最常为NSDictionary,其次为NSArray
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error
把 Foundation json object转换成NSData json object,第一个参数 (id)obj 就是 Foundation json object, Foundation json object的type最常为NSDictionary,其次为NSArray
+ (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error
Check是否Foundation json object符合valid json的格式,能够转换成NSData json object.参数(id)obj就是Foundation json object,Foundation json object的type最常为NSDictionary,其次为NSArray
+ (BOOL)isValidJSONObject:(id)obj
NSJSONSerialization读写json例子: http://www.cnblogs.com/lovecode/articles/2305021.html
注意: MKNetworkKit的responseJSON method是使用NSJSONSerialization,所以responseJSON方法只支持iOS 5!若要连iOS 4都支持,参看 http://stackoverflow.com/questions/8974721/mknetwork-saving-json-content-to-nsdictionary
MKnetworkKit处理json format response的例子:
假设http://xxx.xxx.xxx/cap/jsontest.aspx?action=getnewslist返回的response是json format:
{"category":"Administration","newslist":[{"id":"Y14w5420q122803A526828","title":"news 1"},{"id":"43235trewa323","title":"news 2"}]}
MKNetworkEngine *engine=[[MKNetworkEngine alloc] initWithHostName:@"xxx.xxx.xxx" customHeaderFields:nil]; MKNetworkOperation *op=[engine operationWithPath:@"cap/jsontest.aspx" params:[NSDictionary dictionaryWithObjectsAndKeys: @"getnewslist", @"action", nil] httpMethod:@"GET"]; [op onCompletion:^(MKNetworkOperation *operation) { NSDictionary *response=[operation responseJSON]; NSLog([response objectForKey:@"category"]); for(NSDictionary *newsInfo in [response objectForKey:@"newslist"]) { NSLog([newsInfo objectForKey:@"title"]); } } onError:nil ]; [engine enqueueOperation:op];