将NSString转换为NSDictionary / JSON

我将以下数据保存为NSString

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

我想将这个数据转换为包含键值对的NSDictionary

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

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

但是,当我尝试:

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

我收到的值为NULL

任何人都可以提出什么问题?

我相信你误解了关键值的JSON格式。 你应该存储你的string

 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语句

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

结果将是另一个NSDictionary。

 { Content = 268; type = text; } 

希望这有助于获得清晰的理解。

我想你从响应中获得数组,所以你必须分配响应数组。

  NSError * err = nil;
 NSArray * array = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
 NSDictionary * dictionary = [array objectAtIndex:0]; 
NSString * test = [dictionary objectForKey:@“ID”];
NSLog(@“Test is%@”,test);

其中str是您的JSONstring使用此代码:

 NSError *err = nil; NSArray *arr = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err]; // access the dictionaries NSMutableDictionary *dict = arr[0]; for (NSMutableDictionary *dictionary in arr) { // do something using dictionary } 

Swift 3:

 if let jsonString = styleDictionary as? String { let objectData = jsonString.data(using: String.Encoding.utf8) do { let json = try JSONSerialization.jsonObject(with: objectData!, options: JSONSerialization.ReadingOptions.mutableContainers) print(String(describing: json)) } catch { // Handle error print(error) } } 

使用以下代码从AFHTTPSessionManager失败块获取响应对象,然后可以将genericstypes转换为所需的数据types

id responseObject = [NSJSONSerialization JSONObjectWithData:(NSData *)error.userInfo [AFNetworkingOperationFailingURLResponseDataErrorKey] options:0 error:nil];