IOS开发中JSON常用转换

JSON是一种新的用于在互联网上进行数据交换的标准格式。由于它的冗余、可读性和可解析性都比XML要好,因此JSON这种数据交换格式越来越广泛地运用于Web应用,尤其是Ajax应用中。

在Cocoa中使用JSON也很简单,目前有两个JSON的框架,都很容易使用,而且都对NSDictionary进行了扩展,您可以选择其一将JSON“揉”到您的Cocoa应用程序里。

一个叫做BSJSonAdditions, 由Blake Seely开发。将NSDictionary对象转成JSON字符串只需要进行如下转换:

[dict jsonStringValue];

就可以返回一个NSString的JSON格式。

反过来如果希望将JSON字符串转成NSDictionary,只需要进行如下转换:

 

[NSDictionarydictionaryWithJSONString: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];
de>NSString* stringData =[[NSString alloc] initWithData:yourData                                             encoding:NSUTF8StringEncoding];de>
de>NSDictionary* jsonDictionary =[NSDictionary dictionaryWithObject:stringData                                                           forKey:@"code"];de>
de>NSString* jsonString =[jsonDictionary JSONRepresentation];de>
de>NSDictionary* responseDict =[yourJSONResponseStringFromServer JSONValue];NSNumber* answerNum =(NSNumber*)[responseDict objectForKey:@"answer"];int answer =[answerNum intValue];de>


 

另一个叫做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:

Depending on what's in the buffer (and if your server can handle it) you may want to Base64 encode the result (check http://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):

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

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:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值