【问题标题】:Swift - Using Decodable to decode JSON array of just stringsSwift - 使用 Decodable 来解码 JSON 字符串数组
【发布时间】:2019-07-24 08:27:23
【问题描述】:

我有一个示例 JSON,它只是一个字符串数组,没有键,我想使用 Decodable 协议来使用 JSON 并从中创建一个简单的模型。

json 看起来像这样:

{ "names": [ "Bob", "Alice", "Sarah"] }

只是一个简单数组中的字符串集合。

我不确定如何使用新的 Swift Decodable 协议将其读入没有密钥的模型中。

我见过的大多数示例都假设 JSON 有一个键。

IE:

// code from: Medium article: https://medium.com/@nimjea/json-parsing-in-swift-2498099b78f

struct User: Codable{
       var userId: Int
       var id: Int
       var title: String
       var completed: Bool
}

do {
    //here dataResponse received from a network request
    let decoder = JSONDecoder()
    let model = try decoder.decode([User].self, from:
                 dataResponse) //Decode JSON Response Data 
    print(model)
} catch let parsingError {
    print("Error", parsingError)
}

上面这个例子假设json是一个key-value;如何使用 decodeable 协议在没有密钥的情况下对 JSON 进行解码?

感谢

【问题讨论】:

  • 重要的是要注意您当前的用户模型与当前的 json 无关
  • “我见过的大多数示例都假设 JSON 有一个密钥。”您的 JSON 确实有一个密钥。
  • 对不起,我可能错过了那个

标签: json swift


【解决方案1】:

这个JSON对应的struct是

struct User: Decodable {
   let names: [String]
}

解码

let model = try decoder.decode(User.self, from: dataResponse)

并使用

获取名称
let names = model.names

或者传统上没有JSONDecoder的开销

let model = try JSONSerialization.jsonObject(with: dataResponse) as? [String:[String]]

【讨论】:

  • 或者干脆let names = try decoder.decode(User.self, from: dataResponse).names
【解决方案2】:

对于这种简单的 json 结构,我想最好不要创建任何结构并使用

let model = try decoder.decode([String:[String]].self, from: dataResponse)
print(model["names"])

适合您模型的 json 是

{

    "names": [{ 
          "userId": 2,
         "id": 23,
         "title": "gdgg",
         "completed": true

    }]
}


struct Root: Codable {
    let names: [User]
}

struct User: Codable {
    let userId, id: Int
    let title: String
    let completed: Bool

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2018-04-10
    • 2018-01-19
    • 2018-10-21
    相关资源
    最近更新 更多