现在的位置: 首页 > 综合 > 正文

在Cocoa中使用JSON

2013年10月20日 ⁄ 综合 ⁄ 共 2185字 ⁄ 字号 评论关闭

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 data to one of these formats. Since your data is NSData easiest way is to convert it with:

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 one item with key de<codede< and value de<stringDatade< (from last step):

de<NSDictionary* jsonDictionary = [NSDictionary dictionaryWithObject:stringData
                                                           forKey:@"code"];
de<

This can be easily converted to JSON. Just import JSON.h in your code header, then use:

de<NSString* jsonString = [jsonDictionary JSONRepresentation];
de<

Dump it out and you'll see your JSON string -- something like: { de<"code" : "{yourstringdata}"; }de<. Easiest way to send this over to your server is to use the ASIHTTPRequest library
with a POST method.

Once you get the result back from the server the JSON framework can parse it back into a dictionary and then you can get out the data you need:

de<NSDictionary* responseDict = [yourJSONResponseStringFromServer JSONValue];
NSNumber* answerNum = (NSNumber *) [responseDict objectForKey:@"answer"];
int answer = [answerNum intValue];
de<

 

抱歉!评论已关闭.