将NSString转换为NSDictionary/JSON [英] Converting NSString to NSDictionary / JSON

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

问题描述

我将以下数据另存为NSString:

 {
    Key = ID;
    Value =         {
        Content = 268;
        Type = Text;
    };
},
    {
    Key = ContractTemplateId;
    Value =         {
        Content = 65;
        Type = Text;
    };
},

我想将此数据转换为包含键值对的NSDictionary.

I want to convert this data to an NSDictionary containing the key value pairs.

我首先尝试将NSString转换为 JSON 对象,如下所示:

I am trying first to convert the NSString to a JSON objects as follows :

 NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

但是,当我尝试时:

NSString * test = [json objectForKey:@"ID"];
NSLog(@"TEST IS %@", test);

我收到的值为NULL.

任何人都可以建议出什么问题吗?

Can anyone suggest what is the problem ?

推荐答案

我认为您误解了键值的JSON格式.您应该将字符串存储为

I believe you are misinterpreting the JSON format for key values. You should store your string as

NSString *jsonString = @"{\"ID\":{\"Content\":268,\"type\":\"text\"},\"ContractTemplateID\":{\"Content\":65,\"type\":\"text\"}}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

现在,如果您遵循NSLog语句

Now if you do following NSLog statement

NSLog(@"%@",[json objectForKey:@"ID"]);

结果将是另一个NSDictionary.

Result would be another NSDictionary.

{
    Content = 268;
    type = text;
}

希望这有助于获得清晰的了解.

Hope this helps to get clear understanding.

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

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