2

Can somebody enlighten me how to implement codable protocol to swift structs, for the following json array of multiple types?

In the following json array of materials, it can be reflection object, video or note objects.

{
  "materials": [
    {
      "reflection": {
        "title": "3-2-1 reflection",
        "description": "please reflect after today",
        "questions": [
          {
            "question": "question 1",
            "answer": "answer 1",
            "answerImageUrl": "http://xxx"
          },
          {
            "question": "question 1",
            "answer": "answer 1",
            "answerImageUrl": "http://xxx"
          }
        ]
      }
    },
    {
      "video": {
        "title": "the jungle",
        "description": "please watch after today lesson",
        "videoUrl": "http://"
      }
    },
    {
      "note": {
        "title": "the note",
        "description": "please read after today lesson"
      }
    }
  ]
}

1 Answer 1

2

If you can live with a Material that has three optional properties, this is quite straightforward:

struct Response: Codable {
    let materials: [Material]
}

struct Material: Codable {
    let reflection: Reflection?
    let video: Video?
    let note: Note?
}

struct Video: Codable {
    let title, description, videoUrl: String
}

struct Reflection: Codable {
    let title, description: String
    let questions: [Question]
}

struct Question: Codable {
    let question, answer, answerImageUrl: String
}

struct Note: Codable {
    let title, description: String
}

let response = JSONDecoder().decode(Response.self, from: data)
Sign up to request clarification or add additional context in comments.

7 Comments

The other "harder" way is using enum - but you will need to implement Codable protocol methods for it, e.g. something like in this example code (based on @Gereon answer)
thank so much @MikhailChurbanov (: your answer seems more precise but what's the difference though, why should use enum for this case instead of above answers?
@Gereon, what do you think about Mikhail answer?
Absolutely agree with @Gereon - it's all about usage and personal taste. As for me if it's something not too big and stable (in some way) I would choose the if let - if over-complication doesn't bring you benefits, then it's more harmful than useful. The enums on the other hand are imho better in complex dynamic (evolving) projects - for example if you add a new type to support - exhaustive requirement for switch statements would be a great help in automatically finding all the places where you need to handle it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.