I'm trying to make inherited data model in order to parse it with JSONDecoder.
class FirstClass : Codable {
let firstClassProperty: Int
final let arrayOfInts: [Int]
}
class SecondClass : FirstClass {
let secondClassProperty1: Int
let secondClassProperty2: Int
private enum CodingKeys : String, CodingKey {
case secondClassProperty1, secondClassProperty2
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
secondClassProperty1 = try container.decode(Int.self, forKey: .secondClassProperty1)
secondClassProperty2 = try container.decode(Int.self, forKey: .secondClassProperty2)
try super.init(from: decoder)
}
}
I use this JSON for FirstClass:
{
"firstClassProperty": 123,
"arrayOfInts": [
123
]
}
and this for SecondClass:
{
"firstClassProperty": {},
"secondClassProperty1": {},
"secondClassProperty2": {}
}
How can I get rid of arrayOfInts in my subclass but let it be in superclass if keyword final doesn't work in this case?
Here's Playground. Thanks for your answers!
A quick hack is to declare it as optional. For instance:
class FirstClas: Codable {
let firstClassProperty: Int
final let arrayOfInts: [Int]?
}
That would work around a missing arrayOfInts automatically.
Manual solution. Another solution is to implement the Decodable protocol yourself — as you did in SecondClass — and decode arrayOfInts using decodeIfPresent (and use a default value otherwise).
Superclass decoding. By the way, the recommended way to forward the Decoder to the superclass is by using superDecoder() method:
...
let superDecoder = try container.superDecoder()
try super.init(from: superDecoder)
You can use like this :
class FirstClass : Codable {
let firstClassProperty: Int
final let arrayOfInts: [Int]?
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
firstClassProperty = try container.decode(Int.self, forKey: .firstClassProperty)
arrayOfInts = try container.decodeIfPresent([Int].self, forKey: .arrayOfInts)
}
}
Related
In my custom initializer I'd like to decode a dictionary from JSON and then assign its values to properties in the class. To my surprise, compiler does not allow me to decode the dictionary, I get the error:
Value of protocol type 'Any' cannot conform to 'Decodable'; only struct/enum/class types can conform to protocols
If I try to decode dictionary of type [String: Decodable] the error message says:
Value of protocol type 'Decodable' cannot conform to 'Decodable'; only struct/enum/class types can conform to protocols
My initializer looks like this:
public let total: Int
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
...
if let dict = try container.decodeIfPresent([String: Any].self, forKey: .tracks),
let value = dict["total"] as? Int { // Error is displayed at this line
total = value
} else {
total = 0
}
...
}
When I looked for the answer I found this answer and according to it the code above should not cause any problems.
What you are looking for is nestedContainer. It helps you "skip" a hierarchy level in your JSON. Ie: let's imagine that in your code, it's all in the same level (one struct), but in the JSON, it's not, there is a sub dictionary.
For test purpose, your JSON might look like:
{
"title": "normal",
"tracks": {
"name": "myName",
"total": 3
}
}
If we want in our model:
struct TestStruct: Codable {
let title: String
let name: String
let total: Int
}
We need to use nestedContainer(keyedBy: forKey:):
extension TestStruct {
enum TopLevelKeys: String, CodingKey {
case title
case tracks
}
enum NestedLevelCodingKeys: String, CodingKey {
case name
case total
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: TopLevelKeys.self)
self.title = try container.decode(String.self, forKey: .title)
let subcontainer = try container.nestedContainer(keyedBy: NestedLevelCodingKeys.self, forKey: TopLevelKeys.tracks)
self.name = try subcontainer.decode(String.self, forKey: .name)
self.total = try subcontainer.decode(Int.self, forKey: .total) //You can use here a `decodeIfPresent()` if needed, use default values, etc.
}
}
In your sample, you used decodeIfPresent() for the subdictionary. It's unclear if it was for test purpose, or if the sub dictionary was sometimes not present.
If that's the case and you can have a JSON like this:
{
"title": "normal"
}
Then, before calling nestedContainer(keyedBy: forKey:), use if container.contains(TopLevelKeys.tracks) {} and set default values if needed in the else case.
Here is the code I am using,
struct CreatePostResponseModel : Codable{
var transcodeId:String?
var id:String = ""
enum TopLevelCodingKeys: String, CodingKey {
case _transcode = "_transcode"
case _transcoder = "_transcoder"
}
enum CodingKeys:String, CodingKey{
case id = "_id"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: TopLevelCodingKeys.self)
if let transcodeId = try container.decodeIfPresent(String.self, forKey: ._transcode) {
self.transcodeId = transcodeId
}else if let transcodeId = try container.decodeIfPresent(String.self, forKey: ._transcoder) {
self.transcodeId = transcodeId
}
}
}
Here, transcodeId is decided by either _transcode or _transcoder.
But I want id and rest of the keys (not included here) to be automatically decoded. How can I do it ?
You need to manually parse all the keys once you implement init(from:) in the Codable type.
struct CreatePostResponseModel: Decodable {
var transcodeId: String?
var id: String
enum CodingKeys:String, CodingKey{
case id, transcode, transcoder
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decodeIfPresent(String.self, forKey: .id) ?? ""
if let transcodeId = try container.decodeIfPresent(String.self, forKey: .transcode) {
self.transcodeId = transcodeId
} else if let transcodeId = try container.decodeIfPresent(String.self, forKey: .transcoder) {
self.transcodeId = transcodeId
}
}
}
In the above code,
In case you only want to decode the JSON, there is no need to use Codable. Using Decodable is enough.
Using multiple enums for CodingKey seems unnecessary here. You can use a single enum CodingKeys.
If the property name and the key name is an exact match, there is no need to explicitly specify the rawValue of that case in enum CodingKeys. So, there is no requirement of "_transcode" and "_transcoder" rawValues in TopLevelCodingKeys.
Apart from all that, you can use keyDecodingStrategy as .convertFromSnakeCase to handle underscore notation (snake case notation), i.e.
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase //here.....
let model = try decoder.decode(CreatePostResponseModel.self, from: data)
print(model)
} catch {
print(error)
}
So, you don't need to explicitly handle all the snake-case keys. It'll be handled by the JSONDecoder on its own.
This can be one of the good solution for you wherever you want you can add multiple keys for one variable:
var transcodeId:String?
public init(from decoder: Decoder) throws {
do {
let container = try decoder.container(keyedBy: CodingKeys.self)
transcodeId = container.getValueFromAvailableKey(codingKeys: [CodingKeys._transcoder,CodingKeys._transcode])
} catch {
print("Error reading config file: \(error.localizedDescription)")
}
}
extension KeyedDecodingContainerProtocol{
func getValueFromAvailableKey(codingKeys:[CodingKey])-> String?{
for key in codingKeys{
for keyPath in self.allKeys{
if key.stringValue == keyPath.stringValue{
do{
return try self.decodeIfPresent(String.self, forKey: keyPath)
} catch {
return nil
}
}
}
}
return nil
}
}
Hope it helps.
The compiler-generated init(from:) is all-or-nothing. You can’t have it decode some keys and “manually” decode others.
One way to use the compiler-generated init(from:) is by giving your struct both of the possible encoded properties, and make transcodeId a computed property:
struct CreatePostResponseModel: Codable {
var transcodeId: String? {
get { _transcode ?? _transcoder }
set { _transcode = newValue; _transcoder = nil }
}
var _transcode: String? = nil
var _transcoder: String? = nil
var id: String = “”
// other properties
}
Swift 4 added the new Codable protocol. When I use JSONDecoder it seems to require all the non-optional properties of my Codable class to have keys in the JSON or it throws an error.
Making every property of my class optional seems like an unnecessary hassle since what I really want is to use the value in the json or a default value. (I don't want the property to be nil.)
Is there a way to do this?
class MyCodable: Codable {
var name: String = "Default Appleseed"
}
func load(input: String) {
do {
if let data = input.data(using: .utf8) {
let result = try JSONDecoder().decode(MyCodable.self, from: data)
print("name: \(result.name)")
}
} catch {
print("error: \(error)")
// `Error message: "Key not found when expecting non-optional type
// String for coding key \"name\""`
}
}
let goodInput = "{\"name\": \"Jonny Appleseed\" }"
let badInput = "{}"
load(input: goodInput) // works, `name` is Jonny Applessed
load(input: badInput) // breaks, `name` required since property is non-optional
You can implement the init(from decoder: Decoder) method in your type instead of using the default implementation:
class MyCodable: Codable {
var name: String = "Default Appleseed"
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let name = try container.decodeIfPresent(String.self, forKey: .name) {
self.name = name
}
}
}
You can also make name a constant property (if you want to):
class MyCodable: Codable {
let name: String
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let name = try container.decodeIfPresent(String.self, forKey: .name) {
self.name = name
} else {
self.name = "Default Appleseed"
}
}
}
or
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? "Default Appleseed"
}
Re your comment: With a custom extension
extension KeyedDecodingContainer {
func decodeWrapper<T>(key: K, defaultValue: T) throws -> T
where T : Decodable {
return try decodeIfPresent(T.self, forKey: key) ?? defaultValue
}
}
you could implement the init method as
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decodeWrapper(key: .name, defaultValue: "Default Appleseed")
}
but that is not much shorter than
self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? "Default Appleseed"
You can use a computed property that defaults to the desired value if the JSON key is not found.
class MyCodable: Decodable {
var name: String { return _name ?? "Default Appleseed" }
var age: Int?
// this is the property that gets actually decoded/encoded
private var _name: String?
enum CodingKeys: String, CodingKey {
case _name = "name"
case age
}
}
If you want to have the property read-write, you can also implement the setter:
var name: String {
get { _name ?? "Default Appleseed" }
set { _name = newValue }
}
This adds a little extra verbosity as you'll need to declare another property, and will require adding the CodingKeys enum (if not already there). The advantage is that you don't need to write custom decoding/encoding code, which can become tedious at some point.
Note that this solution only works if the value for the JSON key either holds a string or is not present. If the JSON might have the value under another form (e.g. it's an int), then you can try this solution.
Approach that I prefer is using so called DTOs - data transfer object.
It is a struct, that conforms to Codable and represents the desired object.
struct MyClassDTO: Codable {
let items: [String]?
let otherVar: Int?
}
Then you simply init the object that you want to use in the app with that DTO.
class MyClass {
let items: [String]
var otherVar = 3
init(_ dto: MyClassDTO) {
items = dto.items ?? [String]()
otherVar = dto.otherVar ?? 3
}
var dto: MyClassDTO {
return MyClassDTO(items: items, otherVar: otherVar)
}
}
This approach is also good since you can rename and change final object however you wish to.
It is clear and requires less code than manual decoding.
Moreover, with this approach you can separate networking layer from other app.
You can implement.
struct Source : Codable {
let id : String?
let name : String?
enum CodingKeys: String, CodingKey {
case id = "id"
case name = "name"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
id = try values.decodeIfPresent(String.self, forKey: .id) ?? ""
name = try values.decodeIfPresent(String.self, forKey: .name)
}
}
I came across this question looking for the exact same thing. The answers I found were not very satisfying even though I was afraid that the solutions here would be the only option.
In my case, creating a custom decoder would require a ton of boilerplate that would be hard to maintain so I kept searching for other answers.
I ran into this article that shows an interesting way to overcome this in simple cases using a #propertyWrapper. The most important thing for me, was that it was reusable and required minimal refactoring of existing code.
The article assumes a case where you'd want a missing boolean property to default to false without failing but also shows other different variants.
You can read it in more detail but I'll show what I did for my use case.
In my case, I had an array that I wanted to be initialized as empty if the key was missing.
So, I declared the following #propertyWrapper and additional extensions:
#propertyWrapper
struct DefaultEmptyArray<T:Codable> {
var wrappedValue: [T] = []
}
//codable extension to encode/decode the wrapped value
extension DefaultEmptyArray: Codable {
func encode(to encoder: Encoder) throws {
try wrappedValue.encode(to: encoder)
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
wrappedValue = try container.decode([T].self)
}
}
extension KeyedDecodingContainer {
func decode<T:Decodable>(_ type: DefaultEmptyArray<T>.Type,
forKey key: Key) throws -> DefaultEmptyArray<T> {
try decodeIfPresent(type, forKey: key) ?? .init()
}
}
The advantage of this method is that you can easily overcome the issue in existing code by simply adding the #propertyWrapper to the property. In my case:
#DefaultEmptyArray var items: [String] = []
Hope this helps someone dealing with the same issue.
UPDATE:
After posting this answer while continuing to look into the matter I found this other article but most importantly the respective library that contains some common easy to use #propertyWrappers for these kind of cases:
https://github.com/marksands/BetterCodable
If you don't want to implement your encoding and decoding methods, there is somewhat dirty solution around default values.
You can declare your new field as implicitly unwrapped optional and check if it's nil after decoding and set a default value.
I tested this only with PropertyListEncoder, but I think JSONDecoder works the same way.
If you think that writing your own version of init(from decoder: Decoder) is overwhelming, I would advice you to implement a method which will check the input before sending it to decoder. That way you'll have a place where you can check for fields absence and set your own default values.
For example:
final class CodableModel: Codable
{
static func customDecode(_ obj: [String: Any]) -> CodableModel?
{
var validatedDict = obj
let someField = validatedDict[CodingKeys.someField.stringValue] ?? false
validatedDict[CodingKeys.someField.stringValue] = someField
guard
let data = try? JSONSerialization.data(withJSONObject: validatedDict, options: .prettyPrinted),
let model = try? CodableModel.decoder.decode(CodableModel.self, from: data) else {
return nil
}
return model
}
//your coding keys, properties, etc.
}
And in order to init an object from json, instead of:
do {
let data = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
let model = try CodableModel.decoder.decode(CodableModel.self, from: data)
} catch {
assertionFailure(error.localizedDescription)
}
Init will look like this:
if let vuvVideoFile = PublicVideoFile.customDecode($0) {
videos.append(vuvVideoFile)
}
In this particular situation I prefer to deal with optionals but if you have a different opinion, you can make your customDecode(:) method throwable
I am trying auto parsing an API with swift 4 codable. Some of the fields in the API are big integer which Codable does not support nor Swift 4.NSNumber is not supported by Codable and UInt64 is small for it to fit. I tried with a thrid party library and made my variable within the codable to that type,but that also did not work. I tried to to make a custom class or struct which will do the conversion with only one value in container but don't know how to make the container accept Big Int type or convert it to string.
My code is below like this. Is there any solution to it?
import Foundation
import BigNumber
class PersonalizationLean:Codable {
var hubId:String?
var appId:UInt8?
var nodeId:Int?
var name:String?
var ico:String?
var icoBase64:String?
var isBin:Bool?
var lastModifiedAt:Int?
var shouldShowInUi:Bool?
var applianceType:String?
var tags:[String]?
var placeId:PlaceIdCodable?
var roomId:String?
var id:String?
var key:String?
enum CodingKeys:String,CodingKey {
case hubId
case appId
case nodeId
case name
case ico
case icoBase64
case isBin
case lastModifiedAt
case shouldShowInUi
case applianceType
case tags
case placeId
case roomId
case id
case key
}
// required init(from decoder: Decoder) throws {
// do {
// let container = try decoder.container(keyedBy: CodingKeys.self)
// self.hubId = try container.decode(String.self, forKey: .hubId)
// self.appId = try container.decode(UInt8.self, forKey: .appId)
// self.nodeId = try container.decode(Int.self, forKey: .nodeId)
// self.name = try container.decode(String.self, forKey: .name)
// self.ico = try container.decode(String.self, forKey: .ico)
// self.icoBase64 = try container.decode(String.self, forKey: .icoBase64)
// self.isBin = try container.decode(Bool.self, forKey: .isBin)
// self.lastModifiedAt = try container.decode(Int.self, forKey: .lastModifiedAt)
// self.shouldShowInUi = try container.decode(Bool.self, forKey: .shouldShowInUi)
// self.applianceType = try container.decode(String.self,forKey: .applianceType)
// self.tags = try container.decode([String].self,forKey: .tags)
//
//
// }catch {
// print(error)
// }
// }
}
class PlaceIdCodable:Codable {
var placeId:String?
required init(from decoder:Decoder) throws {
do {
let container = try decoder.singleValueContainer()
let placeIdBig = try container.decode(BInt.self) //this gives error
}catch {
print(error)
}
}
}
The library I am using is BigNumber
Use built-in Decimal which derives from NSDecimalNumber. It adopts Codable
BInt do not conform to Codable OR Decodable
to use it here it should confirm to mentioned protocol
extension BInt: Decodable {
public init(from decoder: Decoder) throws {
// Initialization goes here
}
}
Is it possible that CodingKey can be used for only JSONEncoder and for JSONDecoder use default member names ?
Example I have following structure
var str = """
{
"name": "Endeavor",
"abv": 8.9,
"brewery": "Saint Arnold",
"style": "ipa"
}
"""
enum BeerStyle:String,Codable {
case ipa
case stout
case kolsch
}
struct Beer : Codable {
let name : String
let brewery : String
let style : BeerStyle
let abv : Float
// THIS SHOULD BE USED ONLY FOR JSONEncoder ?
enum CodingKeys:String,CodingKey {
case name
case abv = "alcohol_by_volume"
case brewery = "brewery_name"
case style
}
}
let jsonData = str.data(using: .utf8)!
let decoder = JSONDecoder() // how to to make it not to use Coding key
let beer = try! decoder.decode(Beer.self, from: jsonData)
will not work fine since enum CodingKeys:String,CodingKey is there
Any one can suggest me a idea or link ?
Try this:
Add two enums one for encoding and one for decoding, e.g. EncodingKeys and DecodingKeys
Write custom init(from decoder: Decoder) and encode(to encoder: Encoder) implementations like this.
.
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: EncodingKeys.self)
try container.encode(name, forKey: .name)
// ...
}
and
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: DecodingKeys.self)
name = try values.decode(String.self, forKey: .name)
// ...
}
Update
I tried it with just one implementation of encode(...). You just need to rename the Enum to EncodingKeys.self (or something else). Then implement the encode-function like described above. For decoding the CodingKeys and init-function are being synthesized.