Home > Software engineering >  Having problems mapping down the json data
Having problems mapping down the json data

Time:04-25

I am having problems with mapping down some json data that are coming from the API, A lot of errors are coming and I am really having a difficult time dealing with this one since I am new to swift.

Structure:

{
  "StatusCode": 0,
  "Result": [
   {
     "Type": "Test",
     "Date": "Test",
     "Message": "Test"
   },
   {
     "Type": "Test",
     "Date": "Test",
     "Message": "Test"
   }
 ]
}

My Structure That is not Working:

struct Notifications: Decodable {
    struct NotificationsStructure: Decodable {
    
    var Type: String?
    var Date: String?
    var Message: String?
   }

   var StatusCode: Int
   var Result: NotificationsStructure!
}

CodePudding user response:

First of all never declare a property in a Decodable object as implicit unwrapped optional. If it can be missing or be nil declare it as regular optional (?) otherwise non-optional.

In JSON there are only two collection types:

  • dictionary represented by {},
  • array represented by []

The value for key Result is clearly an array.

And add CodingKeys to map the capitalized keys to lowercase property names

struct Notifications: Decodable {
    struct NotificationsStructure: Decodable {

        private enum CodingKeys: String, CodingKey {
            case type = "Type", date = "Date", message = "Message"
        }
    
        let type: String
        let date: String
        let message: String
   }

   private enum CodingKeys: String, CodingKey {
        case statusCode = "StatusCode", result = "Result",
   }

   let statusCode: Int
   let result: [NotificationsStructure]
}

CodePudding user response:

The response from result is an array type . You should create another object that have same properties of each array.

struct NotificationResponse : Decodable {
   let StatusCode : Int
   let Result: [Notification]
}

struct Notification : Decodable {
   let Type: String
   let Date: String
   let Message: String
}
  • Related