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 the key value pairs.
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];
However when I try :
NSString * test = [json objectForKey:@"ID"];
NSLog(@"TEST IS %@", test);
I receive the value as NULL
.
Can anyone suggest what is the problem ?
This question is related to
objective-c
xcode
json
nsstring
nsdictionary
I think you get the array from response so you have to assign response to 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);
Use the following code to get the response object from the AFHTTPSessionManager
failure block; then you can convert the generic type into the required data type:
id responseObject = [NSJSONSerialization JSONObjectWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] options:0 error:nil];
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)
}
}
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
}
Source: Stackoverflow.com