How can you deserialize an escaped JSON string with NSJSONSerialization?

If you have nested JSON, then just call JSONObjectWithData twice: NSString *string = @”\”{ \\\”name\\\” : \\\”Bob\\\”, \\\”age\\\” : 21 }\””; // –> the string // “{ \”name\” : \”Bob\”, \”age\” : 21 }” NSError *error; NSString *outerJson = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error]; // –> the string // { “name” : “Bob”, “age” : … Read more

JSON.NET serialize JObject while ignoring null properties

You can use a recursive helper method like the one below to remove the null values from your JToken hierarchy prior to serializing it. using System; using Newtonsoft.Json.Linq; public static class JsonHelper { public static JToken RemoveEmptyChildren(JToken token) { if (token.Type == JTokenType.Object) { JObject copy = new JObject(); foreach (JProperty prop in token.Children<JProperty>()) { … Read more

how to prevent NSJSONSerialization from adding extra escapes in URL

This worked for me NSDictionary *policy = ….; NSData *policyData = [NSJSONSerialization dataWithJSONObject:policy options:kNilOptions error:&error]; if(!policyData && error){ NSLog(@”Error creating JSON: %@”, [error localizedDescription]); return; } //NSJSONSerialization converts a URL string from http://… to http:\/\/… remove the extra escapes policyStr = [[NSString alloc] initWithData:policyData encoding:NSUTF8StringEncoding]; policyStr = [policyStr stringByReplacingOccurrencesOfString:@”\\/” withString:@”https://stackoverflow.com/”]; policyData = [policyStr dataUsingEncoding:NSUTF8StringEncoding];

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