How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)
It looks like you are passing an NSString
parameter where you should be passing an NSData
parameter:
NSError *jsonError;
NSData *objectData = [@"{\"2\":\"3\"}" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
How to convert a JSON string to a dictionary?
Warning: this is a convenience method to convert a JSON string to a dictionary if, for some reason, you have to work from a JSON string. But if you have the JSON data available, you should instead work with the data, without using a string at all.
Swift 3
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
let str = "{\"name\":\"James\"}"
let dict = convertToDictionary(text: str)
Swift 2
func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
} catch let error as NSError {
print(error)
}
}
return nil
}
let str = "{\"name\":\"James\"}"
let result = convertStringToDictionary(str)
Original Swift 1 answer:
func convertStringToDictionary(text: String) -> [String:String]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
var error: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:String]
if error != nil {
println(error)
}
return json
}
return nil
}
let str = "{\"name\":\"James\"}"
let result = convertStringToDictionary(str) // ["name": "James"]
if let name = result?["name"] { // The `?` is here because our `convertStringToDictionary` function returns an Optional
println(name) // "James"
}
In your version, you didn't pass the proper parameters to NSJSONSerialization
and forgot to cast the result. Also, it's better to check for the possible error. Last note: this works only if your value is a String. If it could be another type, it would be better to declare the dictionary conversion like this:
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error) as? [String:AnyObject]
and of course you would also need to change the return type of the function:
func convertStringToDictionary(text: String) -> [String:AnyObject]? { ... }
File with string in JSON format , how to read filecontent into NSDictionary
Get the file's data using NSData
's dataWithContentsOfFile
method (the file path should be the path to the file in the bundle; there is a method that can get you the path of a resource from the app main bundle).
Then use NSJSONSerialization
's JSONObjectWithData
method to create a NSDictionary
from the JSON data.
IOS - How to convert json string into object
Your response is not in proper json format. First add the below line to remove the extra empty result string by following line:
yourJsonString = [yourJsonString stringByReplacingOccurrencesOfString:@"{\"result\":[]}" withString:@""];
Then, Try out the below code:
yourJsonString = [yourJsonString stringByReplacingOccurrencesOfString:@"{\"result\":[]}" withString:@""];
NSData* jsonData = [yourJsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *responseObj = [NSJSONSerialization
JSONObjectWithData:jsonData
options:0
error:&error];
if(! error) {
NSArray *responseArray = [responseObj objectForKey:@"result"];
for (NSDictionary *alternative in responseArray) {
NSArray *altArray = [alternative objectForKey:@"alternative"];
for (NSDictionary *transcript in altArray) {
NSLog(@"transcript : %@",[transcript objectForKey:@"transcript"]);
}
}
} else {
NSLog(@"Error in parsing JSON");
}
parse JSON string to NSDictionary into array of objects Objective C
Try this code to get value
NSMutableArray *res = [NSJSONSerialization JSONObjectWithData:GETReply options:NSJSONReadingMutableLeaves|| NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",res);
// get item id
NSLog(@"item-id :%@",[[res objectAtIndex:0] objectForKey:@"item_id"]);
NSLog(@"datetime %@",[[res objectAtIndex:0] objectForKey:@"datetime"]);
NSLog(@"main_url %@",[[res objectAtIndex:0] objectForKey:@"main_url"]);
or get all value from response
for (int i=0; i< res.count; i++){
NSLog(@"item-id :%@",[[res objectAtIndex:i] objectForKey:@"item_id"]);
NSLog(@"datetime %@",[[res objectAtIndex:i] objectForKey:@"datetime"]);
NSLog(@"main_url %@",[[res objectAtIndex:i] objectForKey:@"main_url"]);
}
how to convert NSString into NSDictionary?
Please check with this.
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSDictionary *segueDictionary = [userInfo valueForKey:@"aps"];
NSLog(@"%@",userInfo);
NSDictionary *vendorDic = [segueDictionary valueForKey:@"vendor_data"];
NSString *vedorAddress = [vendorDic valueForKey:@"vendor_address"];
}
Note: in {key:value,key:value} is dictionary formate.but value itself may be a dictionary. i.e {key:{key:value},key:{key:value,key:value}}
How to convert String to dictionary iOS Objective C
Yo need to create a valid JSON first:
NSString *validJsonString = [@"[{ 'langkey':'Arabic','value':'المملكة العربية السعودية'} ,{ 'langkey':'English','value':'Saudi Arabia'} ]" stringByReplacingOccurrencesOfString:@"'" withString:@"\""];
Then, do this:
How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)
Related Topics
Determine on Iphone If User Has Enabled Push Notifications
Why Nsuserdefaults Failed to Save Nsmutabledictionary in Ios
How to Get the Day of the Week With Foundation
In Swift, How to Declare a Variable of a Specific Type That Conforms to One or More Protocols
How to Use Facebook iOS Sdk on iOS 10
Didselectrowatindexpath Not Working, Swift 3
Uitableviewcell, Show Delete Button on Swipe
Zooming Mkmapview to Fit Annotation Pins
Is There a Good Charting Library For Iphone
What Is an "Unwrapped Value" in Swift
How to Compress of Reduce the Size of an Image Before Uploading to Parse as Pffile? (Swift)
String Replacement in Objective-C
Ios 7 Textkit - How to Insert Images Inline With Text
Ineligible Devices Section Appeared in Xcode 6.X.X
Set Initial Viewcontroller in Appdelegate - Swift
How to Mimic the Bottom Sheet from the Maps App
How to Detect Orientation Change
How to Reload Data in a Tableview from a Different Viewcontroller in Swift