解决方法
获取格式化的JSON字符串.
解决方案是从JSON字符串创建JSON对象,
然后使用.PrettyPrinted选项将JSON对象转换回JSON String.
代码是
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)")
结果将如下所示