Convert NSString to NSDictionary / JSON

I have the following data saved as an NSString :

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

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

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

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

However, when I try:

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

I get the value as NULL .

Can anyone guess what the problem is?

+66
json objective-c xcode nsstring nsdictionary
Sep 11 '13 at 8:30
source share
5 answers

I believe that you are misinterpreting the JSON format for key values. You must save 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]; 

Now, if you follow the NSLog statement

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

The result will be another NSDictionary.

 { Content = 268; type = text; } 

Hope this helps to get a clear understanding.

+223
Sep 11 '13 at 8:43
source share

I think you get an array from the answer, so you need to assign an answer to the array.

  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);
+13
Sep 11 '13 at 8:43
source share

Use this code where str is your JSON string:

 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 } 
+6
Sep 11 '13 at 8:32
source share

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) } } 
+1
Jun 12 '17 at 23:31 on
source share

Use the code below to get the response object from the AFHTTPSessionManager failure block, then you can convert the generic type to the required data type

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

0
Apr 05 '17 at 11:07 on
source share



All Articles