标签: decodable

带有多维和多类型数组的 Swift 4 JSON 可解码

{
"values":[
[1,1,7,"Azuan Child","Anak Azuan","12345","ACTIVE","Morning",7,12,"2017-11-09 19:45:00"],
[28,1,0,"Azuan Child2","Amran","123456","ACTIVE","Evening",1,29,"2017-11-09 19:45:00"]
]
}
Run Code Online (Sandbox Code Playgroud)

好的,这是我从服务器收到的 json 格式

现在我想将它解码到我的结构中,但仍然没有运气。

struct ChildrenTable: Decodable {
    var values: [[String]]?
}
Run Code Online (Sandbox Code Playgroud)

我在 URLSession 上的调用者方法看起来像这样

URLSession.shared.dataTask(with: request) { (data, response, err) in
        guard let data = data else { return }

        let dataAsString = String(data: data, encoding: .utf8)
        print(dataAsString)

        do {
            let children  = try
                JSONDecoder().decode(ChildrenTable.self, from: data)
                print (children)
        } catch let jsonErr {
            print ("Error serializing json: ", jsonErr)
        }
    }.resume()
Run Code Online (Sandbox Code Playgroud)

我得到的错误是

Error serializing json:  
typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: …
Run Code Online (Sandbox Code Playgroud)

arrays json multidimensional-array swift4 decodable

2
推荐指数
1
解决办法
3188
查看次数

如何解码具有不同类型的JSON属性?

我有一个JSON

{
"tvShow": {
    "id": 5348,
    "name": "Supernatural",
    "permalink": "supernatural",
    "url": "http://www.episodate.com/tv-show/supernatural",
    "description": "Supernatural is an American fantasy horror television series created by Eric Kripke. It was first broadcast on September 13, 2005, on The WB and subsequently became part of successor The CW's lineup. Starring Jared Padalecki as Sam Winchester and Jensen Ackles as Dean Winchester, the series follows the two brothers as they hunt demons, ghosts, monsters, and other supernatural beings in the world. The series is produced …
Run Code Online (Sandbox Code Playgroud)

json swift alamofire swift4 decodable

2
推荐指数
1
解决办法
898
查看次数

使实体关系可编码/可解码时出错

如何在与 coredata NSManagedObject 映射时编码/解码 swift4 codable 中的 NSOrderedSet 变量?

import CoreData
import Foundation

@objc(TestObject)
public class TestObject:NSManagedObject,Encodable
{

@nonobjc public class func fetchRequest() -> NSFetchRequest<TestObject> {
    return NSFetchRequest<TestObject>(entityName: "TestObject")
}


@NSManaged public var testName: String?
@NSManaged public var devices: NSOrderedSet?  // of entity type "Device"

enum CodingKeys: String, CodingKey {
    case testName
    case devices

}
public func encode(to encoder: Encoder) throws {
     var container = encoder.container(keyedBy:CodingKeys.self)
    try container.encode(testName,forKey:.testName)
    try container.encode(devices,forKey:.devices)
}
}

public required convenience init(from decoder: Decoder) throws { …
Run Code Online (Sandbox Code Playgroud)

core-data swift4 codable decodable encodable

2
推荐指数
1
解决办法
637
查看次数

我的结构不符合协议“可解码”/“可编码”

我试图使用 Codable 来保存我正在创建的应用程序中的数据,但是当我将 Codable 放入我的结构中时,我不断收到错误消息:

“ReminderGroups”类型不符合“Decodable”协议

“ReminderGroups”类型不符合“Encodable”协议

struct ReminderGroups: Codable {
    var contentsArray: [ReminderItem] = []
    var reminderName: String = ""
    var reminderItem: UIImage = #imageLiteral(resourceName: "Folder")
}
Run Code Online (Sandbox Code Playgroud)

structure swift codable decodable

2
推荐指数
1
解决办法
5781
查看次数

在 Swift 模型中解码数组(可解码)

我正在从 API 检索 JSON,并且想为我使用的每个端点创建一个模型。

\n\n

所有端点都使用以下格式:

\n\n
{\n  "id": "xxxxxx",\n  "result": {\xe2\x80\xa6},\n  "error": null\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

关键是:

\n\n
    \n
  • id始终是一个字符串
  • \n
  • error可以为或包含键的对象
  • \n
  • result可以为null;一个对象或一个数组。
  • \n
\n\n

我遇到的问题是,在端点之一上,结果是数组的数组:

\n\n
{\n  "id": "xxxxxx",\n  "result": [\n      [\n          "client_id",\n          "name",\n          50,\n          "status"\n      ]\n  ],\n  "error": null\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

正如您所看到的,我有数组的数组,其中值可以是字符串或整数。

\n\n

如何使用 Decodable 协议对其进行解码,然后根据其原始值将这些解码值用作 String 或 Int ?

\n

arrays swift decodable encodable

2
推荐指数
1
解决办法
1158
查看次数

字典的可解码 keyDecodingStrategy 自定义处理

我有以下 JSON 对象:

{
  "user_name":"Mark",
  "user_info":{
    "b_a1234":"value_1",
    "c_d5678":"value_2"
  }
}
Run Code Online (Sandbox Code Playgroud)

我已经JSONDecoder这样设置了:

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
Run Code Online (Sandbox Code Playgroud)

我的Decodable对象看起来像这样:

struct User: Decodable {
    let userName: String
    let userInfo: [String : String]
}
Run Code Online (Sandbox Code Playgroud)

我面临的问题是该.convertFromSnakeCase策略正在应用于字典的键,我希望这种情况不会发生。

// Expected Decoded userInfo
{
  "b_a1234":"value_1",
  "c_d5678":"value_2"
}

// Actual Decoded userInfo
{
  "bA1234":"value_1",
  "cD5678":"value_2"
}
Run Code Online (Sandbox Code Playgroud)

我研究过使用自定义keyDecodingStrategy(但没有足够的信息来以不同方式处理字典)以及我的自定义初始值设定项Decodable结构的自定义初始值设定项(似乎此时键已经被转换)。

处理此问题的正确方法是什么(仅为字典创建键转换异常)?

注意:我更愿意保留蛇形大小写转换策略,因为我的实际 JSON 对象在蛇形大小写中有很多属性。我当前的解决方法是使用 CodingKeys 枚举手动进行蛇形大小写转换。

json swift codable decodable jsondecoder

2
推荐指数
1
解决办法
2569
查看次数

Swift Codable:使用父级的键作为值

我有一个 JSON,其 ID 在根级别:

{
    "12345": {
        "name": "Pim"
    },
    "54321": {
        "name": "Dorien"
    }
}
Run Code Online (Sandbox Code Playgroud)

我的目标是使用 Codable 创建一个同时具有 name 和 ID 属性的 User 对象数组。

struct User: Codable {
    let id: String
    let name: String
}
Run Code Online (Sandbox Code Playgroud)

我知道如何使用带有单个根级别密钥的Codable ,并且知道如何使用未知密钥。但我在这里尝试做的是两者的结合,我不知道下一步该做什么。

这是我到目前为止得到的:(您可以将其粘贴到 Playground 中)

import UIKit

var json = """
{
    "12345": {
        "name": "Pim"
    },
    "54321": {
        "name": "Dorien"
    }
}
"""

let data = Data(json.utf8)

struct User: Codable {
    let name: String
}

let decoder = JSONDecoder() …
Run Code Online (Sandbox Code Playgroud)

swift codable decodable jsondecoder

2
推荐指数
1
解决办法
1728
查看次数

在 swift 中使用“默认值”创建非可选 Codable 的最佳方法

我知道classand的基本概念,struct但是为 API 创建模型以获取数据并告诉我优缺点更有效。

以前我不使用可选的模型。相反,我给了它一些价值。IE

class CompanyInfo : Codable {
    var NameEn : String = ""
    var CityEn : String = ""
    var Website : String = ""
    var Email : String = ""
    var Phone : String = ""
    var Fax : String = ""
}
Run Code Online (Sandbox Code Playgroud)

但是当它null从 API获得一些价值时。即"Fax": null然后应用程序崩溃,因为它无法使用以下行解析数据

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

定义模型的最佳方法是什么,这样我就不需要解开可选项或给它默认值。

xcode ios swift codable decodable

2
推荐指数
1
解决办法
890
查看次数

如何在 Swift 中从自定义编码/解码的 json 中删除数据模型 nil 字段

我正在尝试找到一种干净的方法来删除数据模型可选属性(如果nil在 Swift 中自定义编码/解码我的数据模型)。

我的用例:

import Foundation

public struct Message {
    public let txnID: UUID
    public var userId: String?
    public var messageID: UUID?
    public init(txnID: UUID, userId: String? = nil, messageID: UUID? = nil) {
        self.txnID = txnID
        self.userId = userId
        self.messageID = messageID
    }
}


extension Message: Codable {
    private enum CodingKeys: CodingKey {
        case txnID, userId, messageID
    }

    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        txnID = try container.decode(UUID.self, forKey: .txnID)
        // …
Run Code Online (Sandbox Code Playgroud)

swift codable decodable

2
推荐指数
1
解决办法
2198
查看次数

使用 Swift Decodable 解码异构数组 JSON

这是我正在尝试解码的 JSON。的值objectType决定创建什么对象。

{
  "options": [
    {
      "objectType": "OptionTypeA",
      "label": "optionALabel1",
      "value": "optionAValue1"
    },
    {
      "objectType": "OptionTypeB",
      "label": "optionBLabel",
      "value": "optionBValue"
    },
    {
      "objectType": "OptionTypeA",
      "label": "optionALabel2",
      "value": "optionAValue2"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

假设我有这样定义的 2 个选项类型

{
  "options": [
    {
      "objectType": "OptionTypeA",
      "label": "optionALabel1",
      "value": "optionAValue1"
    },
    {
      "objectType": "OptionTypeB",
      "label": "optionBLabel",
      "value": "optionBValue"
    },
    {
      "objectType": "OptionTypeA",
      "label": "optionALabel2",
      "value": "optionAValue2"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以手动解码每个键itemContainer并在开关盒中创建单独的选项类型对象。但我不想那样做。我怎样才能解码这些对象?

json heterogeneous swift decodable

2
推荐指数
1
解决办法
1303
查看次数