解析JSON数据响应时出错.... Swift.DecodingError.valueNotFound错误

时间:2020-07-23 03:47:18

标签: json swift model decodable

我有一个用于解析JSON数据的模型文件。来自API的数据响应是

{
    "status": 200,
    "data": {
        "profile": {
            "id": 22,
            "mname": "saranya",
            "cname": "r",
            "business_type": "nanny",
            "mcontact": "123-456-7890",
            "memail": "saranpisces19@gmail.com",
            "mzipcode": "BZ12345",
            "maddress": "r block",
            "city": "Saint Andrew",
            "province": "Christ Church",
            "mdesc": null,
            "image": "nanny_22_logo_34.jpeg",
            "mpassword": "saran123",
            "mstatus": 1,
            "memstatus": 1,
            "created_at": "2020-07-17 06:58:14",
            "updated_at": "2020-07-15 07:39:37",
            "company_id": "R222369",
            "sq1": 1,
            "sq2": 2,
            "sq3": 3,
            "sq1a": "test1",
            "sq2a": "test2",
            "sq3a": "test3",
            "skills": "Making them study",
            "billing_address": "true",
            "exp_years": 0,
            "languages": "English,French",
            "step2": 1,
            "recent_booking": "1592281796"
        },
        "business_type": [
            {
                "id": 1,
                "name": "Nanny",
                "author": "",
                "slug": "nanny",
                "price": "20.00",
                "description": "<p>A Nanny is: Healthcare professionals who assist with daily needs for all ages, regularly or on a long term basis. They’re an important part of your love ones life because they provide care and support their emotional needs. Nannies cater to your love ones where and whenever there needed.</p>\r\n<h3>Services</h3>\r\n<ul>\r\n<li>Day/ Night Care</li>\r\n<li>Oversee the safety and well-being of all Babies, Child(ren) or Elderly</li>\r\n<li>Meal prep and feeding</li>\r\n<li>Maintain Routines and schedules laid out by Parents/Guardians/teachers (including bath and bed time)</li>\r\n<li>Deal with potty duties</li>\r\n<li>Arranging play dates and schedules </li>\r\n<li>Accompany children to activities or Elderly to the doctor</li>\r\n<li>Drop off and pick up kids at school or Elderly to Appointments</li>\r\n<li>Light housework. (Laundry/ iron/ clean)</li>\r\n<li>Homework supervision</li>\r\n<li>Walks and special activities</li>\r\n</ul>",
                "short_description": "",
                "image": "",
                "banner": "",
                "status": 1,
                "created_at": "2020-04-02 11:37:50",
                "updated_at": "2020-04-02 11:37:50"
            },
            {
                "id": 2,
                "name": "Child care",
                "author": "",
                "slug": "child-care",
                "price": "2.00",
                "description": "<p>Child Care is:  Childcare professionals who assist parents daily, and regularly. They’re an important part of your child’s life because they provide care and support their emotional needs.They cater to your kids during your absents or even while you are at home.</p>\r\n<h3>Services</h3>\r\n<ul>\r\n<li>Overnight / live in care</li>\r\n<li>Oversee the safety and well-being of child(ren)</li>\r\n<li>Meal Prep and feeding</li>\r\n<li>Maintain/ Develop routines (bath time, bed time)</li>\r\n<li>Help to potty train</li> \r\n<li>Helping with school work</li>\r\n</ul>",
                "short_description": "",
                "image": "",
                "banner": "",
                "status": 1,
                "created_at": "2020-04-02 11:40:47",
                "updated_at": "2020-04-02 11:40:47"
            },
            {
                "id": 3,
                "name": "Baby sitter",
                "author": "",
                "slug": "baby-sitter",
                "price": "3.00",
                "description": "<p>A Baby Sitter is:  Providing short term supervision and care in the comfort of your home while you’re away!</p>\r\n<h3>Services</h3>\r\n<ul>\r\n<li>Day/Night Care </li>\r\n<li>Oversee the safety and well-being of Babies</li>\r\n<li>Meal prep and feeding</li>\r\n<li>Maintain Routines and schedules laid out by Parents/Guardians</li>\r\n</ul>",
                "short_description": "",
                "image": "",
                "banner": "",
                "status": 1,
                "created_at": "2020-04-02 11:41:04",
                "updated_at": "2020-04-02 11:41:04"
            },
            {
                "id": 5,
                "name": "Full time Babysitter",
                "author": "",
                "slug": "full-time-babysitter",
                "price": "20.00",
                "description": "Full time Babysitter",
                "short_description": "",
                "image": "",
                "banner": "",
                "status": 1,
                "created_at": "2020-06-12 14:22:05",
                "updated_at": "2020-06-12 14:22:05"
            }
        ],
        "provinces": [
            "Christ Church",
            "Saint Andrew",
            "Saint George",
            "Saint James",
            "Saint John",
            "Saint Joseph",
            "Saint Lucy",
            "Saint Michael",
            "Saint Peter",
            "Saint Philip",
            "Saint Thomas",
            "Saint Andrew1"
        ],
        "cities": [
            "Christ Church",
            "Saint Andrew",
            "Saint George",
            "Saint James",
            "Saint John",
            "Saint Joseph",
            "Saint Lucy",
            "Saint Michael",
            "Saint Peter",
            "Saint Philip",
            "Saint Thomas",
            "Bridgetown",
            "Test Entry1",
            "Toronto Ontario"
        ],
        "job_categories": [
            {
                "id": 10,
                "name": "Bath",
                "author": "",
                "slug": "bath",
                "price": "0.0",
                "description": "Bath",
                "short_description": "",
                "image": "service_category_1587137092_1.jpg",
                "banner": "",
                "status": 1,
                "created_at": "2020-04-17 11:46:17",
                "updated_at": "2020-04-17 11:46:17"
            },
            {
                "id": 11,
                "name": "Doctor appointments",
                "author": "",
                "slug": "doctor-appointments",
                "price": "60",
                "description": "Doctor appointments",
                "short_description": "",
                "image": "service_category_1592907625_1.jpg",
                "banner": "",
                "status": 1,
                "created_at": "2020-05-20 16:36:46",
                "updated_at": "2020-05-20 16:36:46"
            },
            {
                "id": 8,
                "name": "Feeding",
                "author": "",
                "slug": "feeding",
                "price": "0.0",
                "description": "Feeding",
                "short_description": "",
                "image": "service_category_1587137052_1.jpg",
                "banner": "",
                "status": 1,
                "created_at": "2020-04-17 11:45:16",
                "updated_at": "2020-04-17 11:45:16"
            },
            {
                "id": 3,
                "name": "Homework",
                "author": "",
                "slug": "homework",
                "price": "0.00",
                "description": "Homework help",
                "short_description": "",
                "image": "service_category_1587137012_1.jpg",
                "banner": "",
                "status": 1,
                "created_at": "2020-04-02 09:44:55",
                "updated_at": "2020-04-02 09:44:55"
            },
            {
                "id": 7,
                "name": "Play Time",
                "author": "",
                "slug": "play-time",
                "price": "0.0",
                "description": "Play Time",
                "short_description": "",
                "image": "service_category_1587137036_1.jpg",
                "banner": "",
                "status": 1,
                "created_at": "2020-04-17 11:44:29",
                "updated_at": "2020-04-17 11:44:29"
            },
            {
                "id": 9,
                "name": "Walks",
                "author": "",
                "slug": "walks",
                "price": "0.0",
                "description": "Walks",
                "short_description": "",
                "image": "service_category_1587137072_1.jpg",
                "banner": "",
                "status": 1,
                "created_at": "2020-04-17 11:45:44",
                "updated_at": "2020-04-17 11:45:44"
            }
        ],
        "exp_years": [
            "Please Select",
            "0 to 2 years",
            "3 to 5 years",
            "6 to 10 years",
            "10 to 15 years",
            "15 to 20 years",
            "20 + years"
        ],
        "hour_rate": [
            "Please Select",
            "$0 to $50",
            "$51 to $100",
            "$101 to $150",
            "$151 to $200",
            "$200+"
        ],
        "languages": {
            "": "Please Select",
            "en": "English",
            "fr": "French"
        },
        "questions": [
            {
                "id": 1,
                "question": "What is Your Mothers Maiden Name?",
                "created_at": "2020-04-03 11:35:18",
                "updated_at": "2020-04-03 11:35:18"
            },
            {
                "id": 2,
                "question": "What is your first school name ?",
                "created_at": "2020-04-03 11:35:27",
                "updated_at": "2020-04-03 11:35:27"
            },
            {
                "id": 3,
                "question": "Who is your child hood hero ?",
                "created_at": "2020-04-03 11:35:33",
                "updated_at": "2020-04-03 11:35:33"
            },
            {
                "id": 4,
                "question": "What is your best friend name?",
                "created_at": "2020-04-03 11:36:02",
                "updated_at": "2020-04-03 11:36:02"
            },
            {
                "id": 5,
                "question": "Who is the Prime minister of Canada?",
                "created_at": "2020-05-20 18:08:54",
                "updated_at": "2020-05-20 18:08:54"
            },
            {
                "id": 6,
                "question": "Which is your favorite sports car?",
                "created_at": "2020-06-12 15:18:28",
                "updated_at": "2020-06-12 15:18:28"
            }
        ]
    },
    "msg": "Schedule form data"
}

用于解析JSON数据的模型文件为

import Foundation

// MARK: - UserDataModel
struct UserDataModel: Codable {
    let status: Int
    let data: DataClass
    let msg: String
}

// MARK: - DataClass
struct DataClass: Codable {
    let profile: Profile
    let businessType: [BusinessType]
    let provinces, cities: [String]
    let jobCategories: [BusinessType]
    let expYears, hourRate: [String]
    let languages: Languages
    let questions: [Question]

    enum CodingKeys: String, CodingKey {
        case profile
        case businessType = "business_type"
        case provinces, cities
        case jobCategories = "job_categories"
        case expYears = "exp_years"
        case hourRate = "hour_rate"
        case languages, questions
    }
}

// MARK: - BusinessType
struct BusinessType: Codable {
    let id: Int?
    let name, author, slug, price: String?
    let businessTypeDescription, shortDescription, image, banner: String?
    let status: Int?
    let createdAt, updatedAt: String?

    enum CodingKeys: String, CodingKey {
        case id, name, author, slug, price
        case businessTypeDescription = "description"
        case shortDescription = "short_description"
        case image, banner, status
        case createdAt = "created_at"
        case updatedAt = "updated_at"
    }
}

// MARK: - Languages
struct Languages: Codable {
    let empty, en, fr: String

    enum CodingKeys: String, CodingKey {
        case empty = ""
        case en, fr
    }
}

// MARK: - Profile
struct Profile: Codable {
    let id: Int?
    let mname, cname, businessType, mcontact: String?
    let memail, mzipcode, maddress, city: String?
    let province: String
    let mdesc: String?
    let image, mpassword: String?
    let mstatus, memstatus: Int?
    let createdAt, updatedAt, companyID: String?
    let sq1, sq2, sq3: Int?
    let sq1A, sq2A, sq3A, skills: String?
    let billingAddress: String?
    let expYears: Int?
    let languages: String?
    let step2: Int?
    let recentBooking: String?

    enum CodingKeys: String, CodingKey {
        case id, mname, cname
        case businessType = "business_type"
        case mcontact, memail, mzipcode, maddress, city, province, mdesc, image, mpassword, mstatus, memstatus
        case createdAt = "created_at"
        case updatedAt = "updated_at"
        case companyID = "company_id"
        case sq1, sq2, sq3
        case sq1A = "sq1a"
        case sq2A = "sq2a"
        case sq3A = "sq3a"
        case skills
        case billingAddress = "billing_address"
        case expYears = "exp_years"
        case languages, step2
        case recentBooking = "recent_booking"
    }
}

// MARK: - Question
struct Question: Codable {
    let id: Int
    let question, createdAt, updatedAt: String

    enum CodingKeys: String, CodingKey {
        case id, question
        case createdAt = "created_at"
        case updatedAt = "updated_at"
    }
}

代码中的JSON解析是

func getUserProfileService()
          {
              print("getUserProfileService function",self.usertoken!)
           
           let header: HTTPHeaders = ["Content-Type":"application/json","x-token":self.usertoken!]
           
             AF.request(mainURL+URLS.user.rawValue, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: header).responseJSON { response in
               
               let decoder = JSONDecoder()
               
               do {
                   
                   let user = try decoder.decode(UserDataModel.self, from: response.data!)
                   self.userData = user
                 
                   
                    self.doLabelChange()
               
                  } catch {
                    debugPrint(error)
                  // print(error.localizedDescription)
               }
               
               
           }
    
       }

我在控制台中收到此错误,并且它没有解析JSON数据响应。 错误是

Swift.DecodingError.valueNotFound(Swift.KeyedDecodingContainer<KiddieCare_Nanny.Profile.CodingKeys>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), CodingKeys(stringValue: "profile", intValue: nil)], debugDescription: "Cannot get keyed decoding container -- found null value instead.", underlyingError: nil))

我将所有值都设为可选,那么错误是什么呢?

0 个答案:

没有答案