【问题标题】:Swift JSON validation fails this data from my web api, I do not know whySwift JSON 验证无法通过我的 web api 获取这些数据,我不知道为什么
【发布时间】:2020-06-03 11:17:18
【问题描述】:

这里是快速代码

if JSONSerialization.isValidJSONObject(JSONData) {
   print (":Valid json")
} else {
   let JSONstring = NSString(data: JSONData, encoding: String.Encoding.utf8.rawValue)
   print(JSONstring)
}

这导致'else'部分被执行,并输出转换为字符串的JSON数据,如下所示:

Optional("[{\"nPropertyID\":4,\"sAddress_1\":\"11 Some street\",\"sAddress_2\":\"Some Road\",\"sAddress_3\":\"Toytown\",\"sPostcode\":\"AB1 9XX\",\"dPurchaseCost\":9999.99,\"dtPurchaseDate\":\"2012-10-23T00:00:00\"}]")

【问题讨论】:

  • 什么是JSONData?并且尽量不要使用大写的变量名。
  • 这有关系吗?你仍然可以使用 jsonObject(with:) 来反序列化它,try JSONSerialization.jsonObject(with: data) as! [[String: Any]]
  • 那么,如果 JSONSerialization.isValidJSONObject 给出错误的结果,它的意义何在?很多人推荐使用它。我想知道的是:json字符串真的有什么问题吗?
  • 为此我们需要查看这个 json 字符串。
  • 你看到了。它在原始问题中。

标签: json swift api validation


【解决方案1】:

根据 Apple 文档,您不能将 isValidJSONObjectDataString 对象一起使用(即使输入参数的类型为 Any):

如果给定对象可以转换为 JSON 数据,则返回 YES,NO 除此以外。该对象必须具有以下属性:

  • 顶级对象是 NSArrayNSDictionary
  • 所有对象都是 NSString、NSNumber、NSArray、NSDictionary 或 NSNull
  • 所有字典键都是 NSStrings
  • NSNumber 不是 NaN 或无穷大

您可以使用:

let jsonStr = "[{\"nPropertyID\":4,\"sAddress_1\":\"11 Welch House\",\"sAddress_2\":\"Beaconsfield Road\",\"sAddress_3\":\"Enfield\",\"sPostcode\":\"EN3 6UX\",\"dPurchaseCost\":88000.00,\"dtPurchaseDate\":\"2012-10-23T00:00:00\"}]"

if let jsonDataToVerify = jsonStr.data(using: .utf8)
{
    do {
        _ = try JSONSerialization.jsonObject(with: jsonDataToVerify)
        print("JSON is valid.")
    } catch {
        print("Error deserializing JSON: \(error.localizedDescription)")
    }
}

按照here的建议。

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 2016-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 2021-04-06
    相关资源
    最近更新 更多