Swift - JSon String打印\ n而不是新行

时间:2018-03-02 04:27:49

标签: ios json swift parsing logging

我想知道在记录时是否有任何方法可以以漂亮的格式打印精确的Json字符串。我正在打印一个http请求标题字段,如

let jsonData = try JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted)
let jsonString = String(bytes: jsonData, encoding: String.Encoding.utf8)
MyLogUtil.logVerbose(message: "\(String(describing: jsonString))")

但不是打印下面的预期日志,

{
   "user": {
       name: "Test",
       age: "30"
    }
}

它的打印类似,

{\n"user": {\nname: "Test",\n\nage: "30"\n}\n}\n

如何摆脱这个问题?

修改 @AwaisFayyaz

func requestTest() -> Void {

        let task = URLSession.shared.dataTask(with: URL(string: "https://jsonplaceholder.typicode.com/posts")!) { (data, response, error) in

            do {

                let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
                if let userDict = json["user"] as? NSDictionary {
                    print(userDict)
                }
            }
            catch let error as NSError {

                print("Failed to load: \(error.localizedDescription)")
            }
        }
        task.resume()
    }

上面的代码崩溃了!

enter image description here

1 个答案:

答案 0 :(得分:0)

假设这是您要以漂亮格式打印的输入字符串。然后

let str = "{\"user\":{\"name\":\"Test\",\"age\":\"30\"} }"

然后使用

let data = str.data(using: String.Encoding.utf8, allowLossyConversion: false)!

do {
  let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]

  if let userDict = json["user"] as? NSDictionary {
    print(userDict)
  }


} catch let error as NSError {
  print("Failed to load: \(error.localizedDescription)")
}

我已经实现了代码。请参阅图像中的控制台输出

enter image description here

@Answer to 编辑

您的代码崩溃了,因为JSON正在返回一个数组,并且您强制强制转换为 [String:Any] (不可能)。而是将其强制转换为 NSArray

在这种情况下使用以下代码段

func requestTest() - >无效{

let task = URLSession.shared.dataTask(with: URL(string: "https://jsonplaceholder.typicode.com/posts")!) { (data, response, error) in

  do {
    //cast it as Array
    let usersArray = try JSONSerialization.jsonObject(with: data!, options: []) as! NSArray
    for userDictAny in usersArray {
      //cast the type of userDictAny to NSDictionary
      guard let userDict = userDictAny as? NSDictionary else {
        print("Error. Count not cast as NSDictionary. Going to return")
        return
      }
      print("\n\n\(userDict)\n\n")
      //additionaly, if you want to get value of individual fields from userDict
      if let userId = userDict["userId"] as? Int64 {
        print("Value of userID \(userId)")
      }
      //in the same way get more values if you want from userDict

    }


  }
  catch let error as NSError {

    print("Failed to load: \(error.localizedDescription)")
  }
}
task.resume()
}

请注意,由于数据是字典,因此不会保留原始数据排序。但是你可以看到你的输出格式很好

输出正在运行的代码的快照 output for updated code