Codable自定义类类型属性无法从JSON初始化其自己的属性

时间:2018-02-06 09:39:06

标签: json swift swift4 codable custom-properties

我的Json:

    {  
   "message":"OK",
   "response":[  
      {  
         "article_id":"201802062200722818",
         "lead":"Poliisi vapautti naisen ja otti miehen kiinni. Satakunnan käräjäoikeus vangitsi miehen tiistaina.",
         "headline":"Poliisi epäilee: 19-vuotias raumalaismies piti alaikäistä naista mökillä vankina",
         "title":"Poliisi epäilee: 19-vuotias raumalaismies piti alaikäistä naista mökillä vankina",
         "service_name":"iltalehti",
         "main_image_name":"cae51c694cc7f31257290ff96489f3cf852329a887509621b29a27fbaa0f8894.jpg",
         "category":{  
            "category_name":"kotimaa",
            "description":"Kotimaan uutiset",
            "parent_category":{  
               "category_name":"uutiset",
               "description":"Uutiset",
               "parent_category":null
            }
         },
         "main_image_urls":{  
            "default":"https://img.ilcdn.fi/PcWFp0weItXN2WAWKBXCO_H2VsQ=/510x/img-s3.ilcdn.fi/cae51c694cc7f31257290ff96489f3cf852329a887509621b29a27fbaa0f8894.jpg",
            "size30":"https://img.ilcdn.fi/_LNHr84u93ntg3tX37oHyGBlRNA=/30x/img-s3.ilcdn.fi/cae51c694cc7f31257290ff96489f3cf852329a887509621b29a27fbaa0f8894.jpg",
            "size98":"https://img.ilcdn.fi/r624bQFqaJ3xqrMScif38JH6SBM=/98x/img-s3.ilcdn.fi/cae51c694cc7f31257290ff96489f3cf852329a887509621b29a27fbaa0f8894.jpg",
            "size138":"https://img.ilcdn.fi/dyemZCdMpjAFTnnD5JiYLh3WGJI=/138x/img-s3.ilcdn.fi/cae51c694cc7f31257290ff96489f3cf852329a887509621b29a27fbaa0f8894.jpg",
            "size244":"https://img.ilcdn.fi/2AiJpLa4oLxEDE0jL_LazhOiTMM=/244x/img-s3.ilcdn.fi/cae51c694cc7f31257290ff96489f3cf852329a887509621b29a27fbaa0f8894.jpg",
            "size293":"https://img.ilcdn.fi/iyAZVQ0ufAHrX2inGCiE9QPQjMU=/293x/img-s3.ilcdn.fi/cae51c694cc7f31257290ff96489f3cf852329a887509621b29a27fbaa0f8894.jpg",
            "size310":"https://img.ilcdn.fi/XGmL7EEqo0OR5Vzvbel1hSeTmHI=/310x/img-s3.ilcdn.fi/cae51c694cc7f31257290ff96489f3cf852329a887509621b29a27fbaa0f8894.jpg",
            "size510":"https://img.ilcdn.fi/PcWFp0weItXN2WAWKBXCO_H2VsQ=/510x/img-s3.ilcdn.fi/cae51c694cc7f31257290ff96489f3cf852329a887509621b29a27fbaa0f8894.jpg",
            "size820":"https://img.ilcdn.fi/N-XV5ZqQASGpvUe-3DAcq4i1928=/820x/img-s3.ilcdn.fi/cae51c694cc7f31257290ff96489f3cf852329a887509621b29a27fbaa0f8894.jpg",
            "size1024":"https://img.ilcdn.fi/J5Cm5P2SJMNymHza7s3LdEEvKLg=/1024x/img-s3.ilcdn.fi/cae51c694cc7f31257290ff96489f3cf852329a887509621b29a27fbaa0f8894.jpg"
         },
         "published_at":"2018-02-06T10:42:40+02:00",
         "updated_at":null
      }
   ]
}

我的Codable模型类

Articles.swift

import Foundation
struct Articles : Codable {
    let message : String?
    let response : [Article]?

    enum CodingKeys: String, CodingKey {

        case message = "message"
        case response = "response"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        message = try values.decodeIfPresent(String.self, forKey: .message)
        response = try values.decodeIfPresent([Article].self, forKey: .response)
    }

}

Article.swift

import Foundation
struct Article : Codable {
    let article_id : String?
    let lead : String?
    let headline : String?
    let title : String?
    let service_name : String?
    let main_image_name : String?
    let category : Category?
    let main_image_urls : Main_image_urls?
    let published_at : String?
    let updated_at : String?

    enum CodingKeys: String, CodingKey {

        case article_id = "article_id"
        case lead = "lead"
        case headline = "headline"
        case title = "title"
        case service_name = "service_name"
        case main_image_name = "main_image_name"
        case category
        case main_image_urls
        case published_at = "published_at"
        case updated_at = "updated_at"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        article_id = try values.decodeIfPresent(String.self, forKey: .article_id)
        lead = try values.decodeIfPresent(String.self, forKey: .lead)
        headline = try values.decodeIfPresent(String.self, forKey: .headline)
        title = try values.decodeIfPresent(String.self, forKey: .title)
        service_name = try values.decodeIfPresent(String.self, forKey: .service_name)
        main_image_name = try values.decodeIfPresent(String.self, forKey: .main_image_name)
        category = try Category(from: decoder)
        main_image_urls = try Main_image_urls(from: decoder)
        published_at = try values.decodeIfPresent(String.self, forKey: .published_at)
        updated_at = try values.decodeIfPresent(String.self, forKey: .updated_at)
    }

}

Category.swift

import Foundation
struct Category : Codable {
    let category_name : String?
    let description : String?
    let parent_category : Parent_category?

    enum CodingKeys: String, CodingKey {

        case category_name = "category_name"
        case description = "description"
        case parent_category
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        category_name = try values.decodeIfPresent(String.self, forKey: .category_name)
        description = try values.decodeIfPresent(String.self, forKey: .description)
        parent_category = try Parent_category(from: decoder)
    }

}

Parent_category.swift

import Foundation
struct Parent_category : Codable {
    let category_name : String?
    let description : String?
    let parent_category : String?

    enum CodingKeys: String, CodingKey {

        case category_name = "category_name"
        case description = "description"
        case parent_category = "parent_category"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        category_name = try values.decodeIfPresent(String.self, forKey: .category_name)
        description = try values.decodeIfPresent(String.self, forKey: .description)
        parent_category = try values.decodeIfPresent(String.self, forKey: .parent_category)
    }

}

问题:

我正在尝试使用Codable协议从JSON初始化我的模型类。它适用于本机数据类型(String,Int等),但如果结构包含自定义类型属性对象,则它不会初始化该自定义结构(类)的属性。

示例:CategoryArticle struct中的自定义类型对象。每个自定义类都负责初始化其属性,确认Codable协议并拥有自己的init(from decoder: Decoder)方法。

但不知怎的category和其他自定义类型无法初始化自己的属性。(例如category_name = nil类中的CategoryParent_category和{Main_image_urls也是如此{1}})我得到以下结果:(某些值为零)

控制台登录xcode

po article

▿ Optional<Article>
  ▿ some : Article
    ▿ article_id : Optional<String>
      - some : "201802062200722818"
    ▿ lead : Optional<String>
      - some : "Poliisi vapautti naisen ja otti miehen kiinni. Satakunnan käräjäoikeus vangitsi miehen tiistaina."
    ▿ headline : Optional<String>
      - some : "Poliisi epäilee: 19-vuotias raumalaismies piti alaikäistä naista mökillä vankina"
    ▿ title : Optional<String>
      - some : "Poliisi epäilee: 19-vuotias raumalaismies piti alaikäistä naista mökillä vankina"
    ▿ service_name : Optional<String>
      - some : "iltalehti"
    ▿ main_image_name : Optional<String>
      - some : "cae51c694cc7f31257290ff96489f3cf852329a887509621b29a27fbaa0f8894.jpg"
    ▿ category : Optional<Category>
      ▿ some : Category
        - category_name : nil
        - description : nil
        ▿ parent_category : Optional<Parent_category>
          ▿ some : Parent_category
            - category_name : nil
            - description : nil
            - parent_category : nil
    ▿ main_image_urls : Optional<Main_image_urls>
      ▿ some : Main_image_urls
        - default : nil
        - size30 : nil
        - size98 : nil
        - size138 : nil
        - size244 : nil
        - size293 : nil
        - size310 : nil
        - size510 : nil
        - size820 : nil
        - size1024 : nil
    ▿ published_at : Optional<String>
      - some : "2018-02-06T10:42:40+02:00"
    - updated_at : nil

我错过了什么吗?请帮帮忙: - )

1 个答案:

答案 0 :(得分:2)

Article.swift尝试更改以下行

category = try Category(from: decoder)
main_image_urls = try Main_image_urls(from: decoder)

category = values.decodeIfPresent(Category.self, forKey: .category)
main_image_urls = values.decodeIfPresent(Main_image_urls.self, forKey: .main_image_urls)

你的班级Main_image_urls也应该符合可编码。

您也可以尝试省略init(from decoder: Decoder)方法并让编译器合成它。这在使用自定义CodingKeys枚举时也有效。

<强>更新

同时更改Category.swift

中的以下行
parent_category = try Parent_category(from: decoder)

parent_category = values.decodeIfPresent(Parent_category.self, forKey: .parentCategory)