Best way to display JSON (well formatted) in UITextView or UIWebView in iOS
here's the Objective-C code.
NSString+PrettyPrint.h
@interface NSString (PrettyPrint)
+ (NSString * _Nonnull)prettifiedJsonStringFromData:(nullable NSData *)data;
+ (NSString * _Nonnull)prettifiedStringFromDictionary:(nullable NSDictionary *)dictionary;
@end
NSString+PrettyPrint.m
#import "NSString+PrettyPrint.h"
@implementation NSString (PrettyPrint)
+ (NSString *)prettifiedStringFromDictionary:(nullable NSDictionary *)dictionary {
if (dictionary == nil) { return @"nil"; }
NSMutableString *returnStr = [NSMutableString stringWithString:@"[ \n"];
for (NSString *key in dictionary) {
[returnStr appendFormat:@" %@: %@,\n", key, [dictionary valueForKey:key]];
}
[returnStr appendFormat:@"]"];
return returnStr;
}
+ (NSString *)prettifiedJsonStringFromData:(nullable NSData *)data {
if (data == nil) { return @"nil"; }
NSData *jsonData;
NSError *error = nil;
NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
if (jsonObject == nil) {
return @"nil (json object from data)";
} else {
BOOL isValidJsonObject = [NSJSONSerialization isValidJSONObject:jsonObject];
if (isValidJsonObject) {
NSData *finalData = [NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:&error];
//TODO: error description
NSString *prettyJson = [[NSString alloc] initWithData:finalData encoding:NSUTF8StringEncoding];
return prettyJson;
} else {
return [NSString stringWithFormat:@"%@\n%@", jsonStr, @" (⚠️ Invalid json object ⚠️)\n"];
}
}
}
@end
then call methods when u need to use them.
ex1. Print NSData for body, response ...etc
NSLog(@"body: %@", [NSString prettifiedJsonStringFromData:[request HTTPBody]]);
ex2. Print NSDictionary
NSLog(@"headers: %@", [NSString prettifiedStringFromDictionary:[request allHTTPHeaderFields]]);
Probably you'll get these results in log.
to get formatted JSON string.
The solution is to create JSON Object from JSON string,
and then convert the JSON object back to JSON String, using .PrettyPrinted
option.
The code is
let jsonString = "[{\"person\": {\"name\":\"Dani\",\"age\":\"24\"}},{\"person\": {\"name\":\"ray\",\"age\":\"70\"}}]"
var error: NSError?
//1. convert string to NSData
let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
//2. convert JSON data to JSON object
let jsonObject:AnyObject = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error)!
//3. convert back to JSON data by setting .PrettyPrinted option
let prettyJsonData = NSJSONSerialization.dataWithJSONObject(jsonObject, options: .PrettyPrinted, error: &error)!
//4. convert NSData back to NSString (use NSString init for convenience), later you can convert to String.
let prettyPrintedJson = NSString(data: prettyJsonData, encoding: NSUTF8StringEncoding)!
//print the result
println("\(prettyPrintedJson)")
The result will look like this
Objective-C code
NSString *jsonString = @"[{\"person\": {\"name\":\"Dani\",\"age\":\"24\"}},{\"person\": {\"name\":\"ray\",\"age\":\"70\"}}]";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&error];
NSData *prettyJsonData = [NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:&error];
NSString *prettyPrintedJson = [NSString stringWithUTF8String:[prettyJsonData bytes]];
NSLog(@"%@", prettyPrintedJson);