【问题标题】:Json Parsing at Swift with alamofire使用 alamofire 在 Swift 上解析 Json
【发布时间】:2018-06-18 07:38:59
【问题描述】:

我正在用 alamofire 快速解析 JSON。我正在尝试查看循环我的 json,但我的代码有问题。使用调试器查看代码时,我的应用程序不会进入 if 和 for。我的代码有什么问题? 我必须用“for”循环我的 json 并解析我的 json 数据。

    Alamofire.request(apiToContact, method: .get, encoding: URLEncoding.default, headers: headersq).responseJSON { (response) in
    print(response)
    if response.result.isSuccess {

        guard let resJson = response.result.value else { return }

        print(resJson);
        if let json = response.result.value as? [String:AnyObject] {
            for entry in json {
                print("\(entry)") // this is where everything crashes
            }
        }

     if let JSON = response.result.value as? NSDictionary{
            for entry in JSON {
                print("\(entry)") // this is where everything crashes
            }
        }

    }
    if response.result.isFailure {

    }
}

Print(response) 给出这个 json.:

    SUCCESS: (
    {
        KoorX = "38.414745";
        KoorY = "27.183055";
        Yon = 1;
    },
    {
        KoorX = "38.41474";
        KoorY = "27.18382667";
        Yon = 1;
    },
    {
       KoorX = "38.422255";
       KoorY = "27.15055167";
       Yon = 1;
}

)

【问题讨论】:

  • "SUCCESS:" 这不是来自您的 JSON 吗?那么你的 JSON 是一个字典数组。类似:[[String: Any]]。另外,如果崩溃,请阅读控制台中的错误消息,如果您不明白,请提供给我们。

标签: json swift alamofire


【解决方案1】:

首先,在 Swift 3+ 中,JSON 字典是 [String:Any]

两个问题:

  1. 数组是根对象中键 SUCCESS 的值。
  2. 字典的快速枚举语法是for (key, value) in dictionary

guard let resJson = response.result.value as? [String:Any],
      let success = resJson["SUCCESS"] as? [[String:Any]] else { return }
      for entry in success {
            print(entry)
        }
    } 

【讨论】:

    【解决方案2】:

    此代码可以帮助您

    if let locationJSON = response.result.value
         {
          let locationObject: Dictionary = locationJSON as! Dictionary<String, Any>
           self.dataArray = locationObject["data"]as! NSArray
    
            }
    

    【讨论】:

      猜你喜欢
      • 2020-02-23
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      相关资源
      最近更新 更多