首页 > 解决方案 > 不同类型的 Json 属性

问题描述

我有一个对象,像这样从 json 反序列化。json 属性之一可能具有两种不同的类型(即枚举的原因)

enum CarValues: Codable { // this enum to recognize,what type of value in array we need
    case withParam(ValuesWithParam)
    case withoutParam(ValuesWithoutParam)

    func encode(to encoder: Encoder) throws {
        var container = encoder.unkeyedContainer()
        switch self {
        case .withParam(let v): try container.encode(v)
        case .withoutParam(let v): try container.encode(v)
        }
    }

    func returnId() -> Int?{
        switch self {
        case .withParam(let v):
            return v.params[0].id
        default :
            return nil
        }
    }

    func initValue(value: String){

        switch self {
        case .withParam (var v):
            v.params[0].setValue(valueToAdd: value)
        default:
            _ = ""
        }
    }

    init(from decoder: Decoder) throws {
        let value = try decoder.singleValueContainer()

        if let v = try? value.decode(ValuesWithParam.self) {
            self = .withParam(v)
            return
        } else if let v = try? value.decode(ValuesWithoutParam.self) {
            self = .withoutParam(v)
            return
        }

        throw Values.ParseError.notRecognizedType(value)
    }

    enum ParseError: Error {
        case notRecognizedType(Any)
    }
}

struct ValuesWithParam: Decodable, Encodable{
    var id: Int
    var title: String
    var params: [Car]

}

struct ValuesWithoutParam: Decodable, Encodable{
    var id: Int
    var title: String
}

我想改变这个对象的一些属性,我该怎么做?我尝试在 function 中执行此操作initValue,但是 (var v) - 只有基本对象的副本。

标签: iosjsonswift

解决方案


将您的initValue功能修改为:

mutating func initValue(value: String){
    if case .withParam (var v) = self {
        v.params[0].setValue(valueToAdd: value)
        self = .withParam(v)
    }
}

要更新您的enum值,您必须替换它,并且它需要mutating功能才能这样做。

另外,我switch只替换了一个caseif case.


推荐阅读