在iOS中的UITextView或UIWebView中显示JSON(格式良好)的最佳方法

时间:2015-06-28 13:23:53

标签: ios json

我需要在我的iPhone应用程序中显示SJON。目前我正在获取未格式化的JSON - 就像一个没有缩进的大字符串。

最好的显示方法是什么?

谢谢,

4 个答案:

答案 0 :(得分:12)

获取格式化的JSON字符串。

解决方案是从JSON字符串

创建JSON对象

然后使用.PrettyPrinted选项将JSON对象转换回JSON字符串。

代码是

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)")

结果将如下所示

pretty printed JSON String

答案 1 :(得分:3)

对象代码

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);

答案 2 :(得分:1)

这是 Objective-C 代码。


<块引用>

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

然后在需要使用方法时调用它们。

ex1。为正文、响应等打印 NSData

NSLog(@"body: %@", [NSString prettifiedJsonStringFromData:[request HTTPBody]]);

ex2。打印 NSDictionary

NSLog(@"headers: %@", [NSString prettifiedStringFromDictionary:[request allHTTPHeaderFields]]);

可能你会在日志中得到这些结果。

enter image description here

enter image description here

答案 3 :(得分:0)

请记住,如果要处理Encodable对象,则可以使用JSONEncoder进行漂亮的打印。

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
        
guard let jsonData = try? encoder.encode(obj) else {
    return
}
        
let text = String(decoding: jsonData, as: UTF8.self)
相关问题