Ver código fonte

Make FLEXUtility JSON prettifying more robust.

NSJSONSerialization loves to throw exceptions.
Ryan Olson 11 anos atrás
pai
commit
cca6415c2a
1 arquivos alterados com 11 adições e 3 exclusões
  1. 11 3
      Classes/Utility/FLEXUtility.m

+ 11 - 3
Classes/Utility/FLEXUtility.m

@@ -256,10 +256,18 @@
 
 + (NSString *)prettyJSONStringFromData:(NSData *)data
 {
+    NSString *prettyString = nil;
+    
     id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
-    NSString *jsonString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:NULL] encoding:NSUTF8StringEncoding];
-    // NSJSONSerialization escapes forward slashes. We want pretty json, so run through and unescape the slashes.
-    return [jsonString stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"];
+    if ([NSJSONSerialization isValidJSONObject:jsonObject]) {
+        prettyString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:NULL] encoding:NSUTF8StringEncoding];
+        // NSJSONSerialization escapes forward slashes. We want pretty json, so run through and unescape the slashes.
+        prettyString = [prettyString stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"];
+    } else {
+        prettyString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
+    }
+
+    return prettyString;
 }
 
 @end