将NSData转换为JSON [英] Convert NSData to JSON

查看:1387
本文介绍了将NSData转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 NSData 对象,我需要将它转换为 NSDictionary 对象。

I have a NSData object, i need to convert it a NSDictionary object.

NSData *data = ....;

现在我需要将其转换为 NSDictionary ,我该如何以编程方式执行此操作?

Now i need to convert this to a NSDictionary, How can i do this programatically ?

注意:我将 NSData 保存到<$ c $后c> NSDictionary 我应该能够访问键值 NSDictionary

note: After i save the NSData to the NSDictionary i should be able to access key value pairs of the NSDictionary.

到目前为止,我没有代码来演示我的工作,我只创建了NSData对象,并且没有任何线索可以继续:)

I don't have a code to demonstrate my workings so far, I have only created the NSData object, and have no clue to continue :)

推荐答案

您可以使用以下内容继承MKNetworkOperation并覆盖responseJSON方法:

You can subclass MKNetworkOperation and override the responseJSON method with the following:

-(id) responseJSON
{
    NSString *rawJSON;
    id jsonValue = nil;
    if ((rawJSON = [[NSString alloc] initWithData:[self responseData] encoding:NSUTF8StringEncoding]) != nil) {
        SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
        if ((jsonValue = [jsonParser objectWithString:rawJSON]) == nil) {
            NSLog(@"This string doesn't seem to be JSON: '%@'\nraw Data : '%s'", rawJSON, (char *)[[self responseData] bytes]);
            return [self responseString];
        }
    }
    else {
        NSLog(@"This data doesn't seem to be an UTF8 encoded string: %@", [self responseData]);
        return [self responseString];
    }

    return jsonValue;
}

这篇关于将NSData转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆