将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.