相关疑难解决方法(0)

如何使用Swift Decodable协议解码嵌套的JSON结构?

这是我的JSON

{
    "id": 1,
    "user": {
        "user_name": "Tester",
        "real_info": {
            "full_name":"Jon Doe"
        }
    },
    "reviews_count": [
        {
            "count": 4
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

这是我想要保存的结构(不完整)

struct ServerResponse: Decodable {
    var id: String
    var username: String
    var fullName: String
    var reviewCount: Int

    enum CodingKeys: String, CodingKey {
       case id, 
       // How do i get nested values?
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经查看了Apple的解码嵌套结构的文档,但我仍然不明白如何正确地执行不同级别的JSON.任何帮助都感激不尽.

json swift swift4 codable

71
推荐指数
5
解决办法
3万
查看次数

如何在Codable类型中使用Any

我目前正在处理Codable项目中的类型并遇到问题.

struct Person: Codable
{
    var id: Any
}
Run Code Online (Sandbox Code Playgroud)

id在上面的代码中可以是a String或an Int.这就是id类型的原因Any.

我知道Any不是Codable.

我需要知道的是我如何才能使它发挥作用.

ios swift codable decodable encodable

18
推荐指数
5
解决办法
1万
查看次数

致命错误:Dictionary <String,Any>不符合Decodable,因为Any不符合Decodable

我正在尝试使用swift 4来解析本地json文件:

{
    "success": true,
    "lastId": null,
    "hasMore": false,
    "foundEndpoint": "https://endpoint",
    "error": null
}
Run Code Online (Sandbox Code Playgroud)

这是我正在使用的功能:

    func loadLocalJSON() {

        if let path = Bundle.main.path(forResource: "localJSON", ofType: "json") {
            let url = URL(fileURLWithPath: path)

            do {
                let data  = try Data(contentsOf: url)
                let colors = try JSONDecoder().decode([String: Any].self, from: data)
                print(colors)
            }
            catch { print("Local JSON not loaded")}
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但我一直收到错误:

致命错误:Dictionary不符合Decodable,因为Any不符合Decodable.

我尝试在此stackoverflow页面上使用"AnyDecodable"方法:如何在Swift 4可解码协议中解码具有JSON字典类型的属性, 但它跳转到'catch'语句: catch { print("Local JSON not loaded")使用时.有谁知道如何在Swift 4中解析这个JSON数据?

json ios swift swift4 decodable

6
推荐指数
1
解决办法
1685
查看次数

Swift Codable 嵌套 json 作为字符串

我用于后端调用的服务返回所有这些 json 结构:

{
    "status" : "OK",
    "payload" : **something**
}
Run Code Online (Sandbox Code Playgroud)

哪里的东西可以是一个简单的字符串:

{
    "status" : "OK",
    "payload" : "nothing changed"
}
Run Code Online (Sandbox Code Playgroud)

或嵌套的 json(具有任何属性的任何 json),例如:

{
    "status" : "OK",
    "payload" : {
                    "someInt" : 2,
                    "someString" : "hi",
                    ...
                }
}
Run Code Online (Sandbox Code Playgroud)

这是我的结构:

struct GenericResponseModel: Codable {

    let status:String?
    let payload:String?
}
Run Code Online (Sandbox Code Playgroud)

我想始终将“有效负载”解码为字符串。因此,在第二种情况下,我希望“GenericResponseModel”的有效负载属性包含该字段的 json 字符串,但是如果我尝试解码该响应,则会收到错误消息:

Type 'String' mismatch: Expected to decode String but found a dictionary instead
Run Code Online (Sandbox Code Playgroud)

可以存档我想要的吗?

非常感谢

json swift swift4 codable

5
推荐指数
1
解决办法
1604
查看次数

Swift - 将字典 [String:Any] 编码和解码为 plist

我正在尝试将字典存储在我的类 Marker 中,但它抛出一个错误,指出它不可编码或不可解码。我可以看到错误是由 [String: Any] 引起的,但我该如何解决呢?

var buttonActions : [String: [String: [String:Any]]] = [:]
Run Code Online (Sandbox Code Playgroud)

保存和加载

func saveData() {
    let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("\(fileName).plist")

    let encoder = PropertyListEncoder()
    do {
        let data = try encoder.encode(markerArray)
        try data.write(to: dataFilePath!)
        print("Saved")
    } catch {
        print("Error Encoding \(error)")
    }
}

func loadData() {
    let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("\(fileName).plist")

    if let data = try? Data(contentsOf: dataFilePath!){
        let decoder = PropertyListDecoder()
        do {
            markerArray = try decoder.decode([Marker].self, from: data)
        } catch { …
Run Code Online (Sandbox Code Playgroud)

encoding dictionary nested decode swift

0
推荐指数
1
解决办法
2571
查看次数

标签 统计

swift ×5

codable ×3

json ×3

swift4 ×3

decodable ×2

ios ×2

decode ×1

dictionary ×1

encodable ×1

encoding ×1

nested ×1