【问题标题】:SWIFT Json check if object title existsSWIFT Json 检查对象标题是否存在
【发布时间】:2020-04-17 11:11:42
【问题描述】:

我的代码检查代码是否:“此数据”不为空,我如何检查代码本身是否存在。有些响应可能会给我一个几乎只有时间戳的空 JSON。所以var代码不会在那里。

或者有没有更好的方法来做到这一点?因为我的 JSON 是

“基于文本输入的变量”导致“代码”可能不存在,其中将包含“某些信息”或“”

脚本顶部:

struct Variables: Decodable {
  var code: String
}

typealias DecoderX = [String: Variables]

先前的函数设置来自用户文本的输入,这些输入与数据库进行交叉检查,因此只有在设置了 UserDefault 输入时才会调用 GetInfo

func GetInfo() {

  let Input1 = UserDefaults.standard.string(forKey: “UserInput1”) ?? “”
  let Input2 = UserDefaults.standard.string(forKey: “UserInput2”) ?? “”
  let Input3 = UserDefaults.standard.string(forKey: “UserInput3”) ?? “”
  print(“Input Check 1: \(Input1) \(Input2) \(Input3)”)

  // URL INFO With API key hidden
  let jsonTask = URLSession.shared.dataTask(with: requestURL) { data, response, error in
    if response == response {
      if let data = data, let body = String(data: data, encoding: .utf8) {
        do {
          let json = try? decoder.decode(DeocderX.self, from: data);
          DispatchQueue.main.async {
            print(“Input Check 2: \(json![Input1]!.code) \(json![Input2]!.code) \(json![Input3]!.code)”)
            if json?[Input1]?.code != nil {
              print("Good Information 1")
            } else {
              print("Found Nothing 1")
            }

            if json?[Input2]?.code != nil {
              print("Good Information 2")
            } else {
              print("Found Nothing 2")
            }
            if json?[Input3]?.code != nil {
              print("Good Information 3")
            } else {
              print("Found Nothing 3")
            }    
          }
        // rest of code not applicable

【问题讨论】:

    标签: json swift xcode parsing


    【解决方案1】:

    您可以使用SwiftyJSON 库。你可以在this link找到它

    if let json = try? JSON(data: response.data!){
        if json["yourKey"]["otherKey"].exists() {
            print("exists")
        }
    }
    

    希望对你有帮助...

    【讨论】:

    • 我遇到的一个问题是,当一个在 json 中没有“代码”的情况下返回时,我的所有响应都变为 nil,因为我的结构正在寻找原始数据。有没有办法摆脱 struct ?直接解析?
    • 你可以用这个库来解析它们。 "json["yourKey"]["otherKey"].int" 例如。
    • 你这个绝对的冠军,以前怎么没人告诉过这件事!我正在使用所有嵌套的结构和案例!我只需要添加 swiftyJSON !
    • 不客气,编码愉快。您还可以从它的文档中获得有关此库的更多信息:)
    猜你喜欢
    • 1970-01-01
    • 2022-01-16
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    • 2017-02-14
    • 2017-12-07
    • 2012-07-27
    相关资源
    最近更新 更多