【问题标题】:Get json value with Alamofire使用 Alamofire 获取 json 值
【发布时间】:2016-06-14 14:47:21
【问题描述】:

我从 tax_ncurrency 中的键“Value”中得到了“16”的值。我正在使用 Alamofire 处理 json,但我无法将其分配给我的标签:productTax

    ["data": (
        {
        "tax_n_currency" =         {
            Value = 16;
            Variable = Tax;
        };
    },
        {
        "tax_n_currency" =         {
            Value = USD;
            Variable = Currency;
        };
    }
)]

我的请求。

     Alamofire.request(.GET, url!, parameters: ["accesskey":223344666]).responseJSON { (request, response, result) in

         let json = result.value as! [String:AnyObject]
        print(json)
        let data = json["data"] as! [AnyObject]
        //print(mm)

        let taxnCurrency = data[0]["tax_n_currency"] as! NSDictionary
        print(taxnCurrency)

        if let tax = taxnCurrency["Value"]?.intValue{
            self.productTax.text = "\(tax) %"
            print(tax)
        }
    }

【问题讨论】:

  • let tax = json["Value"]?.intValue => let tax = taxnCurrency["Value"]?.intValue?
  • 我已经注意到一个犯了这个错误,但它说太用“!”当我再次尝试时(所以基本上是 2 次展开)

标签: json swift alamofire


【解决方案1】:

试试:

if let tax = data["data"] as? [AnyObject],
        tax_n_currency = tax["tax_n_currency"] as? [String:AnyObject],
        value = tax_n_currency["Value"] as? Int {
    print(value)
}

【讨论】:

  • 用什么替换什么?
  • if let tax = json["Value"]?.intValue.. 那一行,
  • @EricD,你能告诉我我做得对吗?我可以这样做吗?或者像这样请求别人帮助是不合适的?
  • @Dershowitz123 如果您想与用户讨论,最好让他们加入您的聊天室(但我认为您还没有足够的代表)。作为个人选择,如果 cmets 中的请求没有发布在我的答案中,我通常会忽略它,但也可能有例外——尽管它们很少见。 ;)
  • 我没有足够的代表@EricD。备择方案?? :(
【解决方案2】:

我喜欢使用if 语句来检查变量是否真的设置,您可以使用打印来检查if 语句中是否有get。如果这不起作用,请提供有关 JSON 的更多信息。 编辑:将第一个条件更改为字典数组

 Alamofire.request(.GET, url!, parameters: ["accesskey":223344666]).responseJSON { (request, response, result) in
        var taxnCurrency: Integer!
        let json = result.value as! [String:AnyObject]
        let data = json["data"] as! [[String:AnyObjecy]]

        if let dict = json[0]["tax_n_currency"] {
                      if let tax = dict["Value"] as! Integer {
                          taxnCurrency = tax
                      }
                   }

【讨论】:

  • 我没有更多关于 json 的信息,并且代码首先不起作用:我必须进行强制转换 Optional[String:AnyObject],并在 `if let tax= data["tax_n_xurrency"]作为! ...它说没有下标成员
  • print(result.value) 你可以检查json的结构。您可以这样做并编辑您的问题吗?
  • 那么在第一个if之后,可以打印(json)并粘贴到这里吗?
  • 我编辑了我的答案,我在这里检查了我的 json,我相信你有一个 NSDict 数组。
  • 你能用我的代码编辑你的答案吗?这样我就可以看到了
猜你喜欢
  • 2015-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多