Swift codable, Default Value to Class property when key missing in the JSON











up vote
2
down vote

favorite












As you know Codable is new stuff in swift 4, So we gonna move to this one from the older initialisation process for the Models. Usually we use the following Scenario



class LoginModal
{
let cashierType: NSNumber
let status: NSNumber

init(_ json: JSON)
{
let keys = Constants.LoginModal()

cashierType = json[keys.cashierType].number ?? 0
status = json[keys.status].number ?? 0
}
}


In the JSON cashierType Key may missing, so we giving the default Value as 0



Now while doing this with Codable is quite easy, as following



class LoginModal: Coadable
{
let cashierType: NSNumber
let status: NSNumber
}


as mentioned above keys may missing, but we don't want the Model Variables as optional, So How we can achieve this with Codable.



Thanks










share|improve this question









New contributor




rinku khatri is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • First of all don't use NSNumber in Swift, use Int, Double or Bool. Second of all in this case you have to write custom initializer.
    – vadian
    16 hours ago










  • @vadian Actually we wants to use codable to manage server response. So as mentioned we are already using custom initialiser, is there any way to handle all this with codable?
    – rinku khatri
    16 hours ago










  • You have to implement init(from decoder: and use decodeIfPresent for the affected properties to be able to assign default values.
    – vadian
    16 hours ago















up vote
2
down vote

favorite












As you know Codable is new stuff in swift 4, So we gonna move to this one from the older initialisation process for the Models. Usually we use the following Scenario



class LoginModal
{
let cashierType: NSNumber
let status: NSNumber

init(_ json: JSON)
{
let keys = Constants.LoginModal()

cashierType = json[keys.cashierType].number ?? 0
status = json[keys.status].number ?? 0
}
}


In the JSON cashierType Key may missing, so we giving the default Value as 0



Now while doing this with Codable is quite easy, as following



class LoginModal: Coadable
{
let cashierType: NSNumber
let status: NSNumber
}


as mentioned above keys may missing, but we don't want the Model Variables as optional, So How we can achieve this with Codable.



Thanks










share|improve this question









New contributor




rinku khatri is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • First of all don't use NSNumber in Swift, use Int, Double or Bool. Second of all in this case you have to write custom initializer.
    – vadian
    16 hours ago










  • @vadian Actually we wants to use codable to manage server response. So as mentioned we are already using custom initialiser, is there any way to handle all this with codable?
    – rinku khatri
    16 hours ago










  • You have to implement init(from decoder: and use decodeIfPresent for the affected properties to be able to assign default values.
    – vadian
    16 hours ago













up vote
2
down vote

favorite









up vote
2
down vote

favorite











As you know Codable is new stuff in swift 4, So we gonna move to this one from the older initialisation process for the Models. Usually we use the following Scenario



class LoginModal
{
let cashierType: NSNumber
let status: NSNumber

init(_ json: JSON)
{
let keys = Constants.LoginModal()

cashierType = json[keys.cashierType].number ?? 0
status = json[keys.status].number ?? 0
}
}


In the JSON cashierType Key may missing, so we giving the default Value as 0



Now while doing this with Codable is quite easy, as following



class LoginModal: Coadable
{
let cashierType: NSNumber
let status: NSNumber
}


as mentioned above keys may missing, but we don't want the Model Variables as optional, So How we can achieve this with Codable.



Thanks










share|improve this question









New contributor




rinku khatri is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











As you know Codable is new stuff in swift 4, So we gonna move to this one from the older initialisation process for the Models. Usually we use the following Scenario



class LoginModal
{
let cashierType: NSNumber
let status: NSNumber

init(_ json: JSON)
{
let keys = Constants.LoginModal()

cashierType = json[keys.cashierType].number ?? 0
status = json[keys.status].number ?? 0
}
}


In the JSON cashierType Key may missing, so we giving the default Value as 0



Now while doing this with Codable is quite easy, as following



class LoginModal: Coadable
{
let cashierType: NSNumber
let status: NSNumber
}


as mentioned above keys may missing, but we don't want the Model Variables as optional, So How we can achieve this with Codable.



Thanks







ios swift xcode swift4 codable






share|improve this question









New contributor




rinku khatri is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




rinku khatri is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 13 hours ago









AS Mackay

1,5993816




1,5993816






New contributor




rinku khatri is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 17 hours ago









rinku khatri

133




133




New contributor




rinku khatri is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





rinku khatri is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






rinku khatri is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • First of all don't use NSNumber in Swift, use Int, Double or Bool. Second of all in this case you have to write custom initializer.
    – vadian
    16 hours ago










  • @vadian Actually we wants to use codable to manage server response. So as mentioned we are already using custom initialiser, is there any way to handle all this with codable?
    – rinku khatri
    16 hours ago










  • You have to implement init(from decoder: and use decodeIfPresent for the affected properties to be able to assign default values.
    – vadian
    16 hours ago


















  • First of all don't use NSNumber in Swift, use Int, Double or Bool. Second of all in this case you have to write custom initializer.
    – vadian
    16 hours ago










  • @vadian Actually we wants to use codable to manage server response. So as mentioned we are already using custom initialiser, is there any way to handle all this with codable?
    – rinku khatri
    16 hours ago










  • You have to implement init(from decoder: and use decodeIfPresent for the affected properties to be able to assign default values.
    – vadian
    16 hours ago
















First of all don't use NSNumber in Swift, use Int, Double or Bool. Second of all in this case you have to write custom initializer.
– vadian
16 hours ago




First of all don't use NSNumber in Swift, use Int, Double or Bool. Second of all in this case you have to write custom initializer.
– vadian
16 hours ago












@vadian Actually we wants to use codable to manage server response. So as mentioned we are already using custom initialiser, is there any way to handle all this with codable?
– rinku khatri
16 hours ago




@vadian Actually we wants to use codable to manage server response. So as mentioned we are already using custom initialiser, is there any way to handle all this with codable?
– rinku khatri
16 hours ago












You have to implement init(from decoder: and use decodeIfPresent for the affected properties to be able to assign default values.
– vadian
16 hours ago




You have to implement init(from decoder: and use decodeIfPresent for the affected properties to be able to assign default values.
– vadian
16 hours ago












1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










Use init(from decoder: Decoder) to set the default values in your model.



struct LoginModal: Codable {

let cashierType: Int
let status: Int

enum CodingKeys: String, CodingKey {
case cashierType = "cashierType"
case status = "status"
}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.cashierType = try container.decodeIfPresent(Int.self, forKey: .cashierType) ?? 0
self.status = try container.decodeIfPresent(Int.self, forKey: .status) ?? 0
}
}


Data Reading:



do {
let data = //JSON Data from API
let jsonData = try JSONDecoder().decode(LoginModal.self, from: data)
print("(jsonData.status) (jsonData.cashierType)")
} catch let error {
print(error.localizedDescription)
}





share|improve this answer





















  • Thanks for the reply. Wants to ask one more thing that can we do this directly with the help of dictionary or firstly have convert it to data?
    – rinku khatri
    15 hours ago












  • We should pass the JSON data which is coming from API to JSONDecoder.
    – Sateesh
    14 hours ago












  • We are using firebase from there dictionary is coming in response, so can we us it directly or have to convert it in data.
    – rinku khatri
    14 hours ago












  • You can format the data from dictionary using JSONSerialization and pass it as an argument to JSONDecoder.
    – Sateesh
    14 hours ago











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});






rinku khatri is a new contributor. Be nice, and check out our Code of Conduct.










 

draft saved


draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53237085%2fswift-codable-default-value-to-class-property-when-key-missing-in-the-json%23new-answer', 'question_page');
}
);

Post as a guest
































1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
1
down vote



accepted










Use init(from decoder: Decoder) to set the default values in your model.



struct LoginModal: Codable {

let cashierType: Int
let status: Int

enum CodingKeys: String, CodingKey {
case cashierType = "cashierType"
case status = "status"
}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.cashierType = try container.decodeIfPresent(Int.self, forKey: .cashierType) ?? 0
self.status = try container.decodeIfPresent(Int.self, forKey: .status) ?? 0
}
}


Data Reading:



do {
let data = //JSON Data from API
let jsonData = try JSONDecoder().decode(LoginModal.self, from: data)
print("(jsonData.status) (jsonData.cashierType)")
} catch let error {
print(error.localizedDescription)
}





share|improve this answer





















  • Thanks for the reply. Wants to ask one more thing that can we do this directly with the help of dictionary or firstly have convert it to data?
    – rinku khatri
    15 hours ago












  • We should pass the JSON data which is coming from API to JSONDecoder.
    – Sateesh
    14 hours ago












  • We are using firebase from there dictionary is coming in response, so can we us it directly or have to convert it in data.
    – rinku khatri
    14 hours ago












  • You can format the data from dictionary using JSONSerialization and pass it as an argument to JSONDecoder.
    – Sateesh
    14 hours ago















up vote
1
down vote



accepted










Use init(from decoder: Decoder) to set the default values in your model.



struct LoginModal: Codable {

let cashierType: Int
let status: Int

enum CodingKeys: String, CodingKey {
case cashierType = "cashierType"
case status = "status"
}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.cashierType = try container.decodeIfPresent(Int.self, forKey: .cashierType) ?? 0
self.status = try container.decodeIfPresent(Int.self, forKey: .status) ?? 0
}
}


Data Reading:



do {
let data = //JSON Data from API
let jsonData = try JSONDecoder().decode(LoginModal.self, from: data)
print("(jsonData.status) (jsonData.cashierType)")
} catch let error {
print(error.localizedDescription)
}





share|improve this answer





















  • Thanks for the reply. Wants to ask one more thing that can we do this directly with the help of dictionary or firstly have convert it to data?
    – rinku khatri
    15 hours ago












  • We should pass the JSON data which is coming from API to JSONDecoder.
    – Sateesh
    14 hours ago












  • We are using firebase from there dictionary is coming in response, so can we us it directly or have to convert it in data.
    – rinku khatri
    14 hours ago












  • You can format the data from dictionary using JSONSerialization and pass it as an argument to JSONDecoder.
    – Sateesh
    14 hours ago













up vote
1
down vote



accepted







up vote
1
down vote



accepted






Use init(from decoder: Decoder) to set the default values in your model.



struct LoginModal: Codable {

let cashierType: Int
let status: Int

enum CodingKeys: String, CodingKey {
case cashierType = "cashierType"
case status = "status"
}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.cashierType = try container.decodeIfPresent(Int.self, forKey: .cashierType) ?? 0
self.status = try container.decodeIfPresent(Int.self, forKey: .status) ?? 0
}
}


Data Reading:



do {
let data = //JSON Data from API
let jsonData = try JSONDecoder().decode(LoginModal.self, from: data)
print("(jsonData.status) (jsonData.cashierType)")
} catch let error {
print(error.localizedDescription)
}





share|improve this answer












Use init(from decoder: Decoder) to set the default values in your model.



struct LoginModal: Codable {

let cashierType: Int
let status: Int

enum CodingKeys: String, CodingKey {
case cashierType = "cashierType"
case status = "status"
}

init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.cashierType = try container.decodeIfPresent(Int.self, forKey: .cashierType) ?? 0
self.status = try container.decodeIfPresent(Int.self, forKey: .status) ?? 0
}
}


Data Reading:



do {
let data = //JSON Data from API
let jsonData = try JSONDecoder().decode(LoginModal.self, from: data)
print("(jsonData.status) (jsonData.cashierType)")
} catch let error {
print(error.localizedDescription)
}






share|improve this answer












share|improve this answer



share|improve this answer










answered 16 hours ago









Sateesh

1,058313




1,058313












  • Thanks for the reply. Wants to ask one more thing that can we do this directly with the help of dictionary or firstly have convert it to data?
    – rinku khatri
    15 hours ago












  • We should pass the JSON data which is coming from API to JSONDecoder.
    – Sateesh
    14 hours ago












  • We are using firebase from there dictionary is coming in response, so can we us it directly or have to convert it in data.
    – rinku khatri
    14 hours ago












  • You can format the data from dictionary using JSONSerialization and pass it as an argument to JSONDecoder.
    – Sateesh
    14 hours ago


















  • Thanks for the reply. Wants to ask one more thing that can we do this directly with the help of dictionary or firstly have convert it to data?
    – rinku khatri
    15 hours ago












  • We should pass the JSON data which is coming from API to JSONDecoder.
    – Sateesh
    14 hours ago












  • We are using firebase from there dictionary is coming in response, so can we us it directly or have to convert it in data.
    – rinku khatri
    14 hours ago












  • You can format the data from dictionary using JSONSerialization and pass it as an argument to JSONDecoder.
    – Sateesh
    14 hours ago
















Thanks for the reply. Wants to ask one more thing that can we do this directly with the help of dictionary or firstly have convert it to data?
– rinku khatri
15 hours ago






Thanks for the reply. Wants to ask one more thing that can we do this directly with the help of dictionary or firstly have convert it to data?
– rinku khatri
15 hours ago














We should pass the JSON data which is coming from API to JSONDecoder.
– Sateesh
14 hours ago






We should pass the JSON data which is coming from API to JSONDecoder.
– Sateesh
14 hours ago














We are using firebase from there dictionary is coming in response, so can we us it directly or have to convert it in data.
– rinku khatri
14 hours ago






We are using firebase from there dictionary is coming in response, so can we us it directly or have to convert it in data.
– rinku khatri
14 hours ago














You can format the data from dictionary using JSONSerialization and pass it as an argument to JSONDecoder.
– Sateesh
14 hours ago




You can format the data from dictionary using JSONSerialization and pass it as an argument to JSONDecoder.
– Sateesh
14 hours ago










rinku khatri is a new contributor. Be nice, and check out our Code of Conduct.










 

draft saved


draft discarded


















rinku khatri is a new contributor. Be nice, and check out our Code of Conduct.













rinku khatri is a new contributor. Be nice, and check out our Code of Conduct.












rinku khatri is a new contributor. Be nice, and check out our Code of Conduct.















 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53237085%2fswift-codable-default-value-to-class-property-when-key-missing-in-the-json%23new-answer', 'question_page');
}
);

Post as a guest




















































































Popular posts from this blog

Full-time equivalent

さくらももこ

13 indicted, 8 arrested in Calif. drug cartel investigation