JSON encode with variable value type

I'm trying to get JSON output like so:


{ "day" : "2019-01-01", "bob" : 73, "frank" : 34.3}


So basically my value can be either a string or a number. I can represent that in Swift via `[String: Any]` of course, but that won't pass through a JSONEncoder. Other than making all my numbers strings...how do I handle that?

Replies

You JSON is familiar enough to work with Codable. You have no need to use `[String: Any]`.

import Foundation

let jsonText = """
{ "day" : "2019-01-01", "bob" : 73, "frank" : 34.3}
"""

class MyStruct: Codable {
    var day: String
    var bob: Int
    var frank: Double
}

extension MyStruct: CustomStringConvertible {
    var description: String {
        return "<day=\(day) bob=\(bob) frank=\(frank)>"
    }
}

let jsonData = jsonText.data(using: .utf8)!

do {
    let myObject = try JSONDecoder().decode(MyStruct.self, from: jsonData)
    print(myObject) //-><day=2019-01-01 bob=73 frank=34.3>
} catch {
    print(error)
}


If this is not what you want, you should better try to desribe what is the problem with more examples.

Apologies. I forgot to mention that the people are dynamic, it's not a set list of names that I know at compile time.

Please show concrete example. I guess your JSON contains multiple people, no?

I showed a concrete example in the original post. It's any number of name/value pairs for the numeric values. I'm explicitly trying to not have a 'people' dictionary in there to keep the data in the format that the calling client needs it in so that it doesn't have to transform the data once it arrives.