【问题标题】:How to access specific data in a JSON response in Swift如何在 Swift 中访问 JSON 响应中的特定数据
【发布时间】:2018-01-27 20:31:23
【问题描述】:

当我运行我的 swift 程序时,我得到了这个 JSON 响应。

{
"success": true,
"info": "Groups",
"data": {
    "groups": "[{\"id\":1,\"name\":\"test\",\"user_id\":1,\"active\":null,\"public\":true,\"image_file_name\":null,\"image_content_type\":null,\"image_file_size\":null,\"image_updated_at\":null,\"created_at\":\"2017-10-15T20:40:13.671+01:00\",\"updated_at\":\"2017-10-15T20:40:13.671+01:00\",\"hashtag\":null},{\"id\":4,\"name\":\"test_again\",\"user_id\":1,\"active\":null,\"public\":false,\"image_file_name\":null,\"image_content_type\":null,\"image_file_size\":null,\"image_updated_at\":null,\"created_at\":\"2018-01-16T18:17:06.575+00:00\",\"updated_at\":\"2018-01-16T18:17:06.575+00:00\",\"hashtag\":null}]"
}

但是,我想访问“组”中包含的信息,特别是组的 ID 和名称。有什么简单的方法吗?

【问题讨论】:

  • groups 对应一个字符串,而不是 JSON 数组。 (因为它包含在引号中)提取字符串,然后将其解析为数组。
  • 这正是我需要知道的,谢谢
  • 只是让您知道,如果您以任何方式控制后端或服务,或者可以联系负责它的人;要求他们不要将其作为字符串发送。它打破了所有惯例。
  • 我实际上确实可以访问后端,但我没有自己编写它并且它在 Rails 中,所以我不知道如何去改变它。如果我要更改它,我会将字符串中的所有内容作为嵌套响应发送吗?
  • 是的,没错。

标签: ios json swift parsing networking


【解决方案1】:
let dic  = response["data"] as! [String:Any]

let groups = dic["groups"] as! String

然后用 jsonSerialization 解析组

let id  = data["id"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 2016-07-17
    • 2019-01-12
    • 2017-11-02
    相关资源
    最近更新 更多