0

Okay, so I am stuck at decoding the last item of this particular json by this the model, "payload" is always nil, Inside this "payload" object I can make my own json structure, I am able to decode the "text" but when it comes to the last item which is "payload", it is not working and is always nil.

I am not using any third-party library.

My Model Class.

struct DailougeFlowModel : Decodable {
//    private enum CodingKeys : String, CodingKey {
//        case responseId = "responseId"
//        case queryResult = "queryResult"
//    }
let responseId : String?
let queryResult : QueryResult?
}

 struct QueryResult: Decodable {
 //    private enum CodingKeys : String, CodingKey {
 //        case fulfillmentText = "fulfillmentText"
 //        case fulfillmentMessages = "fulfillmentMessages"
 //    }
let fulfillmentText : String?
let fulfillmentMessages : [FulfillmentMessages]?

}

struct FulfillmentMessages: Decodable {
let text : TextModel?
let payLoad : Questions?
}

struct TextModel: Decodable {
let text : [String]?
}

struct Questions : Decodable{
let questions : [String]?
 }

This json is what I am getting from the dailogeflow(V2). I am integrating a chatbot in the application.

{
"responseId": "2b879f78-cc05-4735-a7e8-067fdb53a81d-f6406966",
"queryResult": {
"fulfillmentMessages": [
  {
    "text": {
      "text": [
        "Text Here"
      ]
    }
  },
  {
    "text": {
      "text": [
        "Another Reply For Hi"
      ]
    }
  },
  {
    "payload": {
      "questions": [
        "Question One",
        "Question Two",
        "Question Three",
        "Question Four"
      ]
    }
  }
]
}
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Shanu Singh
  • 365
  • 3
  • 16

1 Answers1

1

Specify the inner model names as it is in the json response, if you want to specify your own model name then you would need to set an enum in each model just like the first model 'ResponseModel'

// MARK: - ResponseModel
struct ResponseModel: Codable {
    let responseID: String
    let queryResult: QueryResult

    enum CodingKeys: String, CodingKey {
        case responseID = "responseId"
        case queryResult
    }
}

// MARK: - QueryResult
struct QueryResult: Codable {
    let fulfillmentMessages: [FulfillmentMessage]
}

// MARK: - FulfillmentMessage
struct FulfillmentMessage: Codable {
    let text: Text?
    let payload: Payload?
}

// MARK: - Payload
struct Payload: Codable {
    let questions: [String]
}

// MARK: - Text
struct Text: Codable {
    let text: [String]
}
Zeeshan Ahmed
  • 834
  • 8
  • 13
  • 1
    see i specified the inner model names as it is in the json response thats why, if you want to specify your own model name then you would need to set an enum in each model just like the first model 'ResponseModel' – Zeeshan Ahmed Oct 14 '19 at 07:42
  • 1
    A "master" object containing all types of heterogenous data doesn't have to be always the best solution. It works here nevertheless. – Sulthan Oct 14 '19 at 09:04