【问题标题】:Swift - JSON String printing \n instead of new lineSwift - JSON字符串打印\ n而不是新行
【发布时间】:2018-03-02 04:27:49
【问题描述】:

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

上面的代码崩溃了!

【问题讨论】:

  • kkkk jsonString 它已经是一个可选的String?。您需要做的就是打开您的选项。 if let jsonString = ...。即使 Xcode 建议您应该使用,您也可能永远不需要使用 String(describing:) 方法。顺便说一句,使用字符串插值来显示字符串是没有意义的。只需在打开包装后打印您的 jsonString 即可。 print(jsonString) 或在你的情况下MyLogUtil.logVerbose(message: jsonString)
  • 你试过.sortedKeys而不是.prettyPrinted吗?看起来prettyPrinted 中的空白可能会导致问题。
  • @Jake 没用
  • @LeoDabus 感谢您的建议,但是格式错误呢,它仍然会在日志中打印 '\n\n' 内容

标签: ios json swift parsing logging


【解决方案1】:

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

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

我已经实现了代码。查看图片中的控制台输出

@Answer to 编辑

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

在这种情况下使用下面的代码sn-p

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()
}

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

运行代码的输出快照

【讨论】:

  • 你的意思是订单不会被保留?
  • @Sazzad Hissain Khan。您要打印的输入 json 字符串是什么?
  • 我不想投反对票,但您的解决方案仍然不起作用。打印时也一样。
  • 我已经在一个示例字符串上实现了我的解决方案并且工作正常。在我的回答中还包含屏幕截图。你能给我你试图以漂亮格式打印的输入 json 字符串吗?
  • 屏幕截图显示正常,但实际日志与屏幕中的不同。我会尽快分享。
猜你喜欢
  • 1970-01-01
  • 2010-11-07
  • 2018-12-19
  • 1970-01-01
  • 1970-01-01
  • 2017-09-16
  • 2016-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多