JSON是一种新的用于在互联网上进行数据交换的标准格式。由于它的冗余、可读性和可解析性都比XML要好,因此JSON这种数据交换格式越来越广泛地运用于Web应用,尤其是Ajax应用中。
在Cocoa中使用JSON也很简单,目前有两个JSON的框架,都很容易使用,而且都对NSDictionary进行了扩展,您可以选择其一将JSON“揉”到您的Cocoa应用程序里。
一个叫做BSJSonAdditions, 由Blake
Seely开发。将NSDictionary对象转成JSON字符串只需要进行如下转换:
[dict jsonStringValue];
就可以返回一个NSString的JSON格式。
反过来如果希望将JSON字符串转成NSDictionary,只需要进行如下转换:
[NSDictionary dictionaryWithJSONString:jsonString]
就可以返回NSDictionary的对象了。
NSMutableDictionary *dlist = [[NSMutableDictionary alloc] init];
[dlist setObject:@"name1" forKey:@"name"];
NSString *str = [dlist JSONRepresentation];
NSMutableDictionary *d = [str JSONValue];
NSLog(@"%@" , [d description]);
[dlist release];
另一个叫做json-framework,参考了BSJSonAdditions,并且以framework的方式提供。
json- framework的用法同样类似,使用NSDictionary或者NSArray的JSONRepresentation方法来获取JSON的 NSString字符串,用NSString的JSONValue方法来获取转换后的NSDictionary或者NSArray对象。
JSON framework supports converting Arrays, Dictionaries, Strings, Numbers, and Booleans. So what you want to do is convert your da
de<NSString* stringData = [[NSString alloc] initWithData:yourData encoding:NSUTF8StringEncoding]; de<
Depending on what's in the buffer (and if your server can handle it) you may want to Base64 encode the result (checkhttp://www.cocoadev.com/index.pl?BaseSixtyFour if
you don't have a converter handy). You could even go straight from NSData to a Base64-encoded string.
Now create a dictionary with on
de<NSDictionary* jsonDictionary = [NSDictionary dictionaryWithObject:stringData forKey:@"co de"]; de<
This can be easily converted to JSON. Just imp
de<NSString* jsonString = [jsonDictionary JSONRepresentation]; de<
Dump it out and you'll see your JSON string -- something like: {
with a POST method.
On
de<NSDictionary* responseDict = [yourJSONResponseStringFromServer JSONValue]; NSNumber* answerNum = (NSNumber *) [responseDict objectForKey:@"answer"]; int answer = [answerNum intValue]; de<