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

问题描述 投票:0回答:1

我想知道是否有任何方法可以在记录时以漂亮的格式打印精确的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

ios json swift parsing logging
1个回答
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编辑

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

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

func requestTest() - > Void {

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的输出快照

© www.soinside.com 2019 - 2024. All rights reserved.