嗨,我有多个 JSON 数据包,如下所示。
{
"data" : {
"lng" : 36.159999999999997,
"lat" : 50.359999999999999,
"accuracy" : 5
},
"header" : {
"type" : "loc"
}
}
和这个
{
"data" : {
"time" : 15646565455,
"tz" : "+2",
"system" : 5
},
"header" : {
"type" : "syn"
}
}
我的数据包有结构,它适用于一种数据包结构。但是如何将它用于多个数据包结构。
struct Packet : Codable {
enum StructureType : String, Codable {
case location = "loc"
case synchronize = "syn"
}
enum Status: String, Codable {
case OK = "OK"
case NOT = "NOT"
}
struct Header: Codable {
let type: StructureType
let status: Status?
}
var header: Header
struct Data : Codable {
struct LocationStruct : Codable {
var lng: Double
var lat: Double
var accuracy: Double
}
struct SynchronizationStruct: Codable {
var time: Int
var tz: String
var locale: String
}
}
var data: Data
}
现在我想编码 JSON 取决于我的数据
let dataHeader = Packet.Header.init(type: .location, action: nil, ID: nil, dataID: nil, status: nil)
let dataData = Packet.Data.LocationStruct.init(lng: lng, lat: lat, accuracy: acc)
let dataObject = Packet.init(header: dataHeader, data: dataData)
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try! encoder.encode(dataObject)
如何做到这一点,或者我需要为每个数据包使用我的数据结构的其他结构?