nsjsonserialization
NSJSONSerialization from NSString
First you will need to convert your NSString to NSData by doing the following NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding]; then simply use the JSONObjectWithData method to convert it to JSON id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
Swift: Convert struct to JSON?
Swift 4 introduces the Codable protocol which provides a very convenient way to encode and decode custom structs. struct Sentence : Codable { let sentence : String let lang : String } let sentences = [Sentence(sentence: “Hello world”, lang: “en”), Sentence(sentence: “Hallo Welt”, lang: “de”)] do { let jsonData = try JSONEncoder().encode(sentences) let jsonString = … Read more
Could not cast value of type ‘NSTaggedPointerString’ to ‘NSNumber’
The reason of the error is jsonDict[“totalfup”] is a String (NSTaggedPointerString is a subclass of NSString) , so you should convert String to Double. Please make sure, catch exception and check type before force-unwrap ! totalData = (jsonDict[“totalfup”] as! NSString).doubleValue For safety, using if let: // check dict[“totalfup”] is a String? if let totalfup = … Read more
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]? … Read more
Reading in a JSON File Using Swift
Follow the below code : if let path = NSBundle.mainBundle().pathForResource(“test”, ofType: “json”) { if let jsonData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil) { if let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary { if let persons : NSArray = jsonResult[“person”] as? NSArray { // Do stuff } } } } The … Read more