【问题标题】:iOS Swift How to get value of any key from json responseiOS Swift如何从json响应中获取任何键的值
【发布时间】:2021-08-12 17:09:15
【问题描述】:

我收到来自 API 的响应

["response": {
    record =     {
        title = "Order Add";
        usercart = 5345;
    };
}, "status": success, "message": تم إضافة السجل بنجاح]

我从代码中获得了状态键的值

let statusCode = json["status"].string

现在我想要字符串值中键 usercart 的值 我正在使用此代码,但得到任何响应。

let order_id = json["response"]["record"]["usercart"].string

请帮我获取这个值。

【问题讨论】:

  • usercart 也可以是整数。我建议放弃SwiftyJSON,转而使用Codable
  • 如何获取这个值并转换成int
  • 我对@9​​87654327@ 不是很熟悉。使用代码完成。可能是intinteger
  • @vadian SwiftyJSON 自动将 int 转换为字符串。
  • 使用json["response"]["record"]["usercart"].stringValue。安装 string 使用 stringValue

标签: ios json swift key-value


【解决方案1】:

您从服务器获取的 json 是错误的。相反,它应该是 -

["response": {
    "record" : {
        "title" : "Order Add",
        "usercart" : 5345
    };
}, "status": success, "message": تم إضافة السجل بنجاح]

json 中没有像 = 这样的东西

此外,如果服务器响应无法更改,我建议将整个内容读取为字符串,然后在字符串中使用搜索,尽管这是非常糟糕的方法。

【讨论】:

  • 如何获取用户购物车价值?
  • 如果服务器像上面那样发送正确的 json 然后 let order_id = json["response"]["record"]["usercart"].string 这会起作用
  • json["response"]["record"]["usercart"].stringValue 解决我的问题
【解决方案2】:

当您使用SwiftyJSON 并且您试图将usercart 值作为stringusercartInt

因此,如果您希望使用字符串格式,则需要使用.stringValue 而不是.string,否则您可以使用.int.intValue 格式为int

json["response"]["record"]["usercart"].stringValue

【讨论】:

    【解决方案3】:

    如果您使用的是 SwiftyJSON,那么使用它来获取价值

      json["response"]["record"]["usercart"].stringValue
    

    【讨论】:

    • 此答案已发布。有什么新东西吗?
    猜你喜欢
    • 2019-12-31
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多