标签: decodable

字符串字典:任何不符合“可解码”协议

我正在尝试实现一个 Decodable 来解析 json 请求,但 json 请求在对象内部有一个字典。

这是我的代码:

    struct myStruct : Decodable {
        let content: [String: Any]
}

        enum CodingKeys: String, CodingKey {
            case content = "content"
}
Run Code Online (Sandbox Code Playgroud)

但我收到此错误:

类型“MyClass.myStruct”不符合协议“Decodable”

如何在没有此错误的情况下将变量声明为字典?

我会非常感谢你的帮助

swift decodable

4
推荐指数
2
解决办法
6308
查看次数

JSONDecoder 无法处理空响应

语境

我正在使用Firebase 数据库 REST API和 JSONDecoder/JSONEncoder。到目前为止,它一直运行良好。但是,对于删除数据,预期返回的响应是null,而 JSONDecoder 似乎不太喜欢那样。

这是我通过 Postman 发送的查询类型以及我返回的内容(不包括敏感数据)。

DELETE /somedata/-LC03I3oHcLhQ/members/ZnWsJtrZ5UfFS6agajbL2hFlIfG2.json
content-type: application/json
cache-control: no-cache
postman-token: ab722e0e-98ed-aaaa-bbbb-123f64696123
user-agent: PostmanRuntime/7.2.0
accept: */*
host: someapp.firebaseio.com
accept-encoding: gzip, deflate
content-length: 39


HTTP/1.1 200
status: 200
server: nginx
date: Thu, 02 Aug 2018 21:53:27 GMT
content-type: application/json; charset=utf-8
content-length: 4
connection: keep-alive
access-control-allow-origin: *
cache-control: no-cache
strict-transport-security: max-age=31556926; includeSubDomains; preload

null
Run Code Online (Sandbox Code Playgroud)

如您所见,响应代码是200,正文是null

错误

当我收到响应时,这是我得到的错误:

Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data is not …

json firebase swift firebase-realtime-database decodable

4
推荐指数
2
解决办法
1927
查看次数

在 swift 中使用 UUID() 和 json

我在网上找到了在 json 文件中使用硬编码 uuid 的示例,并且这些示例非常适合我,但是当我在应用程序中添加从 json 数组中删除项目的功能时,我需要动态创建这些 uuid

这是我的json文件(list.json),它曾经有硬编码的id,如“id”:1并且有效(当我使用int作为ids时)

[
  {
    "name": "Dune",
    "author": "Frank Herbert",
    "page": "77"
  },
  {
    "name": "Ready Player One",
    "author": "Ernest Cline",
    "page": "234"
  },
  {
    "name": "Murder on the Orient Express",
    "author": "Agatha Christie",
    "page": "133"
  }
]
Run Code Online (Sandbox Code Playgroud)

这是我的结构(Book.swift)

struct Book: Hashable, Codable, Identifiable {
    var id = UUID()
    var name: String
    var author: String
    var page: String
}
Run Code Online (Sandbox Code Playgroud)

当我使用此结构和代码(Data.swift)解码我的 json 文件时...

let bookData: [Book] = load("list.json")

func load<T: Decodable>(_ filename: String) -> T …
Run Code Online (Sandbox Code Playgroud)

json swift codable decodable

4
推荐指数
1
解决办法
4717
查看次数

如何将(Swift4)init添加到Decodable协议

我正在尝试创建一个Codable扩展,它能够仅使用json字符串初始化Decodable(Swift 4)对象.那应该是什么工作:

struct MyObject: Decodable {
   var title: String?
}

let myObject = MyObject(json: "{\"title\":\"The title\"}")
Run Code Online (Sandbox Code Playgroud)

我认为这意味着我应该创建一个使用Decoder调用self.init的init.这是我提出的代码:

public init?(json: String) throws {
    guard let decoder: Decoder = GetDecoder.decode(json: json)?.decoder else { return }
    try self.init(from: decoder) // Who what should we do to get it so that we can call this?
}
Run Code Online (Sandbox Code Playgroud)

该代码能够获取解码器,但是在调用init时出现编译器错误.我得到的错误是:

在self.init电话之前使用'self'

这是否意味着无法在Decodable协议中添加init?

有关完整的源代码,请参阅github上的可编码扩展

更新: 从@appzYourLive调试下面的解决方案后,我发现我与init(json:Decodable和Array上的初始化程序有冲突.我刚刚向GitHub发布了新版本的扩展.我还添加了解决方案作为这个问题的新答案.

json init swift4 codable decodable

3
推荐指数
1
解决办法
3054
查看次数

动态JSON解码Swift 4

我正在尝试在Swift 4中解码以下JSON:

{
    "token":"RdJY3RuB4BuFdq8pL36w",
    "permission":"accounts, users",
    "timout_in":600,
    "issuer": "Some Corp",
    "display_name":"John Doe",
    "device_id":"uuid824fd3c3-0f69-4ee1-979a-e8ab25558421"
}
Run Code Online (Sandbox Code Playgroud)

问题是,JSON中的最后2个元素(display_namedevice_id)可能存在也可能不存在,或者元素可能被命名为完全不同但仍未知的元素,即"fred": "worker", "hours" : 8

所以,我想要实现的是解码什么是已知的,即token,permission,timeout_inissuer任何其他元素(display_name,device_id等),将它们放入一个字典.

我的结构看起来像这样:

struct AccessInfo : Decodable
{
    let token: String
    let permission: [String]
    let timeout: Int
    let issuer: String
    let additionalData: [String: Any]

    private enum CodingKeys: String, CodingKey
    {
        case token
        case permission
        case timeout = "timeout_in"
        case issuer
    }

    public init(from decoder: Decoder) …
Run Code Online (Sandbox Code Playgroud)

json dynamic swift decodable

3
推荐指数
1
解决办法
2501
查看次数

如何从Swift 4中的Decoder容器中获取非解码属性?

我正在使用该 Decodable协议来解析从外部源接收的JSON.在解码了我知道的属性之后,JSON中可能还有一些未知且尚未解码的属性.例如,如果外部源在未来的某个时间点向JSON添加了一个新属性,我希望通过将它们存储在[String: Any]字典(或替代)中来保留这些未知属性,这样就不会忽略这些值.

问题是在解码了我知道的属性之后,容器上没有任何访问器来检索尚未解码的属性.我知道decoder.unkeyedContainer()我可以使用哪个迭代每个值但是这在我的情况下不起作用,因为为了使它工作,你需要知道你正在迭代什么值类型,但JSON中的值类型是并不总是相同.

这是我在游乐场中为我想要实现的目标的一个例子:

// Playground
import Foundation

let jsonData = """
{
    "name": "Foo",
    "age": 21
}
""".data(using: .utf8)!

struct Person: Decodable {
    enum CodingKeys: CodingKey {
        case name
    }

    let name: String
    let unknownAttributes: [String: Any]

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.name = try container.decode(String.self, forKey: .name)

        // I would like to store the `age` attribute in this dictionary
        // but it would not be known …
Run Code Online (Sandbox Code Playgroud)

json ios swift swift4 decodable

3
推荐指数
1
解决办法
1387
查看次数

Swift 4 + Alamofire可解码Json URL格式

我有一个JSON格式,我不能用Alamofire解码.

这是我的json:

"data":[  
{  
    "id":37,
    "status":"A\u00e7\u0131k",
    "department":"Muhasebe",
    "title":"Y\u00f6netim Panelinden Deneme 4 - Mail Kontrol",
    "message":"<p>Y\u00f6netim Panelinden Deneme 4 - Mail Kontrol<br><\/p>",
    "file":null,
    "created_at":{  
        "date":"2018-01-13 01:59:49.000000",
        "timezone_type":3,
        "timezone":"UTC"
    },
    "replies":[  
        {  
            "id":6,
            "ticket_id":37,
            "admin_id":null,
            "user_id":8593,
            "message":"<p>test<\/p>",
            "file":"uploads\/tickets\/8593-P87wd8\/GFV6H5M94y5Pt27YAxZxHNRcVyFjD554i80og3xk.png",
            "created_at":"2018-01-18 11:16:55",
            "updated_at":"2018-01-18 11:16:55"
        }
    ]
},
Run Code Online (Sandbox Code Playgroud)

这是我的JSON模型:

struct TeknikDestek : Decodable {
    var id: Int?
    var status: String?
    var title: String?
    var department: String?
    var message: String?

    var replies: [Replies]?
}

struct Replies: Decodable {
    var replyid: Int?
    var ticket_id: Int?
    var admin_id: …
Run Code Online (Sandbox Code Playgroud)

swift alamofire swift4 decodable

3
推荐指数
1
解决办法
5898
查看次数

使用Swift Codable从JSON数组中提取数据

我有这样的JSON响应:

在此处输入图片说明

我目前将可解码结构设计如下:

    struct PortfolioResponseModel: Decodable {
    var dataset: Dataset

    struct Dataset: Decodable {
        var data: Array<PortfolioData> //I cannot use [Any] here...

        struct PortfolioData: Decodable {
            //how to extract this data ?
        }
    }
   }
Run Code Online (Sandbox Code Playgroud)

问题是,如何提取数组中的数据,该数组的值可以为Double或String。

这是在操场上进行这项工作的示例字符串:

   let myJSONArray =
   """
   {
   "dataset": {
   "data": [
    [
   "2018-01-19",
   181.29
   ],
   [
   "2018-01-18",
   179.8
   ],
   [
   "2018-01-17",
   177.6
   ],
   [
   "2018-01-16",
   178.39
   ]
   ]
   }
   }
   """
Run Code Online (Sandbox Code Playgroud)

提取数据:

do {
    let details2: PortfolioResponseModel = try JSONDecoder().decode(PortfolioResponseModel.self, from: myJSONArray.data(using: .utf8)!)
    //print(details2) 
    //print(details2.dataset.data[0]) //somehow …
Run Code Online (Sandbox Code Playgroud)

json swift swift4 codable decodable

3
推荐指数
1
解决办法
4212
查看次数

预期解码Int但找到一个字符串

我的JSON看起来像:

{
    "status": true,
    "data": {
        "img_url": "/images/houses/",
        "houses": [
            {
                "id": "1",
                "name": "Kapital",
                "url": "https://kapital.com/",
                "img": "10fbf4bf6fd2928affb180.svg"
            }
        ]
     }
 }
Run Code Online (Sandbox Code Playgroud)

我正在使用下一个结构:

struct ServerStatus: Decodable {
    let status: Bool
    let data: ServerData
}

struct ServerData: Decodable {
    let img_url: String
    let houses: [House]
}

struct House: Decodable {
    let id: Int
    let img: String
    let name: String
    let url: String
}
Run Code Online (Sandbox Code Playgroud)

但是当我使用时:

let houses = try JSONDecoder().decode(ServerStatus.self, from: data)
Run Code Online (Sandbox Code Playgroud)

我收到下一个错误:

3 : CodingKeys(stringValue: "id", intValue: nil)
  - debugDescription …
Run Code Online (Sandbox Code Playgroud)

json swift decodable

3
推荐指数
1
解决办法
1281
查看次数

Swift 4可解码,带有未知的动态按键

我有以下JSON

{"DynamicKey":6410,"Meta":{"name":"","page":""}}
Run Code Online (Sandbox Code Playgroud)

DynamicKey在编译时是未知的.我正在尝试查找如何使用decodable解析此结构的引用.

public struct MyStruct: Decodable {
    public let unknown: Double
    public let meta: [String: String]

    private enum CodingKeys: String, CodingKey {
        case meta = "Meta"
    }
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

json swift decodable

3
推荐指数
1
解决办法
822
查看次数