How do I parse a JSON object that has type-dependent sub-objects, in Swift?

后端 未结 1 936
礼貌的吻别
礼貌的吻别 2021-01-24 22:44

I have the following JSON object:

[{
    \"type\": \"foo\",
    \"props\": {
        \"word\": \"hello\"
    }
}, {
    \"type\": \"bar\",
    \"props\": {
              


        
相关标签:
1条回答
  • 2021-01-24 23:00

    Looking at your original listed errors, there are two distinct issues.

    1. You declared conformance to Codable, but the errors are telling you it cannot automatically synthesize Encodable. Your question isn't about encoding, but decoding, so for this I'd say just conform to Decodable instead of Codable (or implement encoding yourself).
    2. props is of type PropTypes?, where PropTypes is an enum. You're decoding either FooProps or BarProps, and stuffing the result into props. You need to wrap the result in the enum instead. Also your enum is defined wrong, you have cases named FooProps and BarProps, which don't carry values. It should be redefined like { case foo(FooProps), bar(BarPros) } instead.

    So together, this would look like

    struct MyObject : Decodable {
        struct FooProps : Decodable { let word: String }
        struct BarProps : Decodable { var number: Int }
        enum PropTypes { case foo(FooProps), bar(BarProps) }
    
        let type: String
        let props: PropTypes?
    
        enum CodingKeys : CodingKey {
            case type, props
        }
    
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            type = try values.decode(String.self, forKey: .type)
            switch type {
            case "foo":
                props = try .foo(values.decode(FooProps.self, forKey: .props))
            case "bar":
                props = try .bar(values.decode(BarProps.self, forKey: .props))
            default:
                props = nil
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题