{"id":2607,"date":"2018-02-16T12:15:00","date_gmt":"2018-02-16T08:15:00","guid":{"rendered":"https:\/\/blog.alwawee.ru\/?p=2607"},"modified":"2018-02-16T12:15:00","modified_gmt":"2018-02-16T08:15:00","slug":"handling-swift-jsondecoder-typemismatch-error-while-using-codable-protocol","status":"publish","type":"post","link":"https:\/\/blog.alwawee.ru\/?p=2607","title":{"rendered":"Handling Swift JSONDecoder typeMismatch error while using Codable protocol"},"content":{"rendered":"<p>If you have a problematic JSON, which can contain number or string for some keys, you can decode object without that property and manually set that property after decoding. <\/p>\n<p>For example, I have a <em>Vehicle<\/em> class inside <em>HistoryItem<\/em>. In Vehicle <em>model_year<\/em> can be empty <em>String<\/em> or non empty <em>Int<\/em>. Here I am decoding <em>modelYear<\/em> manually using <em>NSDictionary<\/em> and trying to get <em>Int<\/em>. <em>Swift 4<\/em> cannot do it automatically.<\/p>\n<pre>\r\n    do {\r\n        \/\/ Decoding HistoryItem from JSON\r\n        let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)\r\n        let decoder = JSONDecoder()\r\n        let historyItem = try decoder.decode(HistoryItem.self, from: jsonData)\r\n        if let modelYear = (dict as NSDictionary).value(forKeyPath: \"vehicle.model_year\") as? Int {\r\n            historyItem.vehicle?.modelYear = modelYear\r\n        }\r\n        \r\n        \/\/ Saving HistoryItem to Realm\r\n        let realm = try! Realm()\r\n        try! realm.write {\r\n            realm.add(historyItem, update: true)\r\n        }\r\n        \r\n    } catch {\r\n        print(error.localizedDescription)\r\n    }\r\n<\/pre>\n<p>This is my <em>Vehicle<\/em> class that is contained inside <em>HistoryItem<\/em>: <\/p>\n<pre>\r\n    class Vehicle: Object, Codable {\r\n        @objc dynamic var VIN: String = \"\"\r\n        @objc dynamic var make: String?\r\n        @objc dynamic var modelName: String?\r\n        @objc dynamic var recallCount: Int = 0\r\n        @objc dynamic var modelYear: Int = 0\r\n        \r\n        override static func primaryKey() -> String? {\r\n            return \"VIN\"\r\n        }\r\n        \r\n        private enum CodingKeys: String, CodingKey {\r\n            case VIN = \"vin\"\r\n            case make\r\n            case modelName = \"model_name\"\r\n            case recallCount = \"recall_count\"\r\n        }\r\n    }\r\n<\/pre>\n<p>As you see, there is no <em>model_year<\/em> key in <em>CodingKeys<\/em>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>If you have a problematic JSON, which can contain number or string for some keys, you can decode object without that property and manually set that property after decoding. For example, I have a Vehicle class inside HistoryItem. In Vehicle model_year can be empty String or non empty Int. Here I am decoding modelYear manually [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3],"tags":[200,201,199],"class_list":["post-2607","post","type-post","status-publish","format-standard","hentry","category-ios","tag-codable","tag-json","tag-swift"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.6 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Handling Swift JSONDecoder typeMismatch error while using Codable protocol - Denis Kutlubaev<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/blog.alwawee.ru\/?p=2607\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Handling Swift JSONDecoder typeMismatch error while using Codable protocol - Denis Kutlubaev\" \/>\n<meta property=\"og:description\" content=\"If you have a problematic JSON, which can contain number or string for some keys, you can decode object without that property and manually set that property after decoding. For example, I have a Vehicle class inside HistoryItem. In Vehicle model_year can be empty String or non empty Int. Here I am decoding modelYear manually [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/blog.alwawee.ru\/?p=2607\" \/>\n<meta property=\"og:site_name\" content=\"Denis Kutlubaev\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/alwaweemobile\" \/>\n<meta property=\"article:published_time\" content=\"2018-02-16T08:15:00+00:00\" \/>\n<meta property=\"og:image\" content=\"http:\/\/blog.alwawee.com\/?attachment_id=1982\" \/>\n<meta name=\"author\" content=\"Denis Kutlubaev\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Denis Kutlubaev\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"1 minute\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/blog.alwawee.ru\\\/?p=2607#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/blog.alwawee.ru\\\/?p=2607\"},\"author\":{\"name\":\"Denis Kutlubaev\",\"@id\":\"https:\\\/\\\/blog.alwawee.ru\\\/#\\\/schema\\\/person\\\/58f1f1f57155b48afab83ba53b3e26a7\"},\"headline\":\"Handling Swift JSONDecoder typeMismatch error while using Codable protocol\",\"datePublished\":\"2018-02-16T08:15:00+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/blog.alwawee.ru\\\/?p=2607\"},\"wordCount\":98,\"commentCount\":0,\"keywords\":[\"Codable\",\"JSON\",\"Swift\"],\"articleSection\":[\"iOS\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/blog.alwawee.ru\\\/?p=2607#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/blog.alwawee.ru\\\/?p=2607\",\"url\":\"https:\\\/\\\/blog.alwawee.ru\\\/?p=2607\",\"name\":\"Handling Swift JSONDecoder typeMismatch error while using Codable protocol - Denis Kutlubaev\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/blog.alwawee.ru\\\/#website\"},\"datePublished\":\"2018-02-16T08:15:00+00:00\",\"author\":{\"@id\":\"https:\\\/\\\/blog.alwawee.ru\\\/#\\\/schema\\\/person\\\/58f1f1f57155b48afab83ba53b3e26a7\"},\"breadcrumb\":{\"@id\":\"https:\\\/\\\/blog.alwawee.ru\\\/?p=2607#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/blog.alwawee.ru\\\/?p=2607\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/blog.alwawee.ru\\\/?p=2607#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/blog.alwawee.ru\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Handling Swift JSONDecoder typeMismatch error while using Codable protocol\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/blog.alwawee.ru\\\/#website\",\"url\":\"https:\\\/\\\/blog.alwawee.ru\\\/\",\"name\":\"Denis Kutlubaev\",\"description\":\"iOS Development\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/blog.alwawee.ru\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/blog.alwawee.ru\\\/#\\\/schema\\\/person\\\/58f1f1f57155b48afab83ba53b3e26a7\",\"name\":\"Denis Kutlubaev\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/346de75d27c818be0aa7fddeada2e50e30cc15b4da6b3b8110c5d766cd2afa34?s=96&d=mm&r=pg\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/346de75d27c818be0aa7fddeada2e50e30cc15b4da6b3b8110c5d766cd2afa34?s=96&d=mm&r=pg\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/346de75d27c818be0aa7fddeada2e50e30cc15b4da6b3b8110c5d766cd2afa34?s=96&d=mm&r=pg\",\"caption\":\"Denis Kutlubaev\"},\"description\":\"iOS Developer, creator of Tornado Browser and many other popular apps\",\"sameAs\":[\"http:\\\/\\\/dennis.alwawee.com\"],\"url\":\"https:\\\/\\\/blog.alwawee.ru\\\/?author=1\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Handling Swift JSONDecoder typeMismatch error while using Codable protocol - Denis Kutlubaev","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/blog.alwawee.ru\/?p=2607","og_locale":"en_US","og_type":"article","og_title":"Handling Swift JSONDecoder typeMismatch error while using Codable protocol - Denis Kutlubaev","og_description":"If you have a problematic JSON, which can contain number or string for some keys, you can decode object without that property and manually set that property after decoding. For example, I have a Vehicle class inside HistoryItem. In Vehicle model_year can be empty String or non empty Int. Here I am decoding modelYear manually [&hellip;]","og_url":"https:\/\/blog.alwawee.ru\/?p=2607","og_site_name":"Denis Kutlubaev","article_publisher":"https:\/\/www.facebook.com\/alwaweemobile","article_published_time":"2018-02-16T08:15:00+00:00","og_image":[{"url":"http:\/\/blog.alwawee.com\/?attachment_id=1982","type":"","width":"","height":""}],"author":"Denis Kutlubaev","twitter_misc":{"Written by":"Denis Kutlubaev","Est. reading time":"1 minute"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/blog.alwawee.ru\/?p=2607#article","isPartOf":{"@id":"https:\/\/blog.alwawee.ru\/?p=2607"},"author":{"name":"Denis Kutlubaev","@id":"https:\/\/blog.alwawee.ru\/#\/schema\/person\/58f1f1f57155b48afab83ba53b3e26a7"},"headline":"Handling Swift JSONDecoder typeMismatch error while using Codable protocol","datePublished":"2018-02-16T08:15:00+00:00","mainEntityOfPage":{"@id":"https:\/\/blog.alwawee.ru\/?p=2607"},"wordCount":98,"commentCount":0,"keywords":["Codable","JSON","Swift"],"articleSection":["iOS"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/blog.alwawee.ru\/?p=2607#respond"]}]},{"@type":"WebPage","@id":"https:\/\/blog.alwawee.ru\/?p=2607","url":"https:\/\/blog.alwawee.ru\/?p=2607","name":"Handling Swift JSONDecoder typeMismatch error while using Codable protocol - Denis Kutlubaev","isPartOf":{"@id":"https:\/\/blog.alwawee.ru\/#website"},"datePublished":"2018-02-16T08:15:00+00:00","author":{"@id":"https:\/\/blog.alwawee.ru\/#\/schema\/person\/58f1f1f57155b48afab83ba53b3e26a7"},"breadcrumb":{"@id":"https:\/\/blog.alwawee.ru\/?p=2607#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/blog.alwawee.ru\/?p=2607"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/blog.alwawee.ru\/?p=2607#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/blog.alwawee.ru\/"},{"@type":"ListItem","position":2,"name":"Handling Swift JSONDecoder typeMismatch error while using Codable protocol"}]},{"@type":"WebSite","@id":"https:\/\/blog.alwawee.ru\/#website","url":"https:\/\/blog.alwawee.ru\/","name":"Denis Kutlubaev","description":"iOS Development","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/blog.alwawee.ru\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/blog.alwawee.ru\/#\/schema\/person\/58f1f1f57155b48afab83ba53b3e26a7","name":"Denis Kutlubaev","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/346de75d27c818be0aa7fddeada2e50e30cc15b4da6b3b8110c5d766cd2afa34?s=96&d=mm&r=pg","url":"https:\/\/secure.gravatar.com\/avatar\/346de75d27c818be0aa7fddeada2e50e30cc15b4da6b3b8110c5d766cd2afa34?s=96&d=mm&r=pg","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/346de75d27c818be0aa7fddeada2e50e30cc15b4da6b3b8110c5d766cd2afa34?s=96&d=mm&r=pg","caption":"Denis Kutlubaev"},"description":"iOS Developer, creator of Tornado Browser and many other popular apps","sameAs":["http:\/\/dennis.alwawee.com"],"url":"https:\/\/blog.alwawee.ru\/?author=1"}]}},"_links":{"self":[{"href":"https:\/\/blog.alwawee.ru\/index.php?rest_route=\/wp\/v2\/posts\/2607","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.alwawee.ru\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.alwawee.ru\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.alwawee.ru\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.alwawee.ru\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=2607"}],"version-history":[{"count":6,"href":"https:\/\/blog.alwawee.ru\/index.php?rest_route=\/wp\/v2\/posts\/2607\/revisions"}],"predecessor-version":[{"id":2613,"href":"https:\/\/blog.alwawee.ru\/index.php?rest_route=\/wp\/v2\/posts\/2607\/revisions\/2613"}],"wp:attachment":[{"href":"https:\/\/blog.alwawee.ru\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=2607"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.alwawee.ru\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=2607"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.alwawee.ru\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=2607"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}