How to represent a generic JSON structure in Swift?

我的梦境 提交于 2019-12-05 08:39:52

We will use generic strings as coding keys:

extension String: CodingKey {
    public init?(stringValue: String) {
        self = stringValue
    }

    public var stringValue: String {
        return self
    }

    public init?(intValue: Int) {
        return nil
    }

    public var intValue: Int? {
        return nil
    }
}

The rest really is just a matter of getting the correct type of container and writing your values to it.

extension JSON: Encodable {
    public func encode(to encoder: Encoder) throws {
        switch self {
        case .string(let string):
            var container = encoder.singleValueContainer()
            try container.encode(string)
        case .number(let number):
            var container = encoder.singleValueContainer()
            try container.encode(number)
        case .object(let object):
            var container = encoder.container(keyedBy: String.self)

            for (key, value) in object {
                try container.encode(value, forKey: key)
            }
        case .array(let array):
            var container = encoder.unkeyedContainer()

            for value in array {
                try container.encode(value)
            }
        case .bool(let bool):
            var container = encoder.singleValueContainer()
            try container.encode(bool)
        case .null:
            var container = encoder.singleValueContainer()
            try container.encodeNil()
        }
    }
}

Given this, I'm sure you can implement Decodable and Equatable yourself.


Note that this will crash if you try to encode anything other than an array or an object as a top-level element.

Welton122

You could use generics for this:

typealias JSON<T: Any> = [String: T] where T: Equatable

You could try this BeyovaJSON

import BeyovaJSON

let foo: JToken = [
    "foo": 1,
    "bar": "baz",
]

let encoded = try JSONEncoder().encode(foo)

I ran into this issue but I had too many types that I want to desserialize so I think I would have to enumerate all of them in the JSON enum from the accepted answer. So I created a simple wraper which worked surprisingly well:

struct Wrapper: Encodable {
    let value: Encodable
    func encode(to encoder: Encoder) throws {
        try value.encode(to: encoder)
    }
}

then you could write

let foo: [String: Wrapper] = [
    "foo": Wrapper(value: 1),
    "bar": Wrapper(value: "baz"),
]

let encoded = try JSONEncoder().encode(foo) // now this works

Not the prettiest code ever, but worked for any type you want to encode without any additional code.

From my point of view the most suitable is SwiftyJSON. It has nice API for the developers to be sure how parse and work with JSON objects.

JSON object have quite nice interface for working with different types of the response.

From the Apple docs:

Types that conform to the Equatable protocol can be compared for equality using the equal-to operator (==) or inequality using the not-equal-to operator (!=). Most basic types in the Swift standard library conform to Equatable.

Let consider case that you ask.We should just check if JSON conforms to protocol Equatable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!