gpt4 book ai didi

具有多种结构的 JSONEncoder

转载 作者:行者123 更新时间:2023-11-28 09:51:04 25 4
gpt4 key购买 nike

您好,我有多个 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)

该怎么做,或者我需要为每个数据包使用我的数据结构的其他结构?

最佳答案

我有两个主要模型对象的结构,LocationSynchronization。然后我将它们定义为符合某些协议(protocol),我们在其中指定了我们如何知道哪个“ header ”适用于哪种类型的有效负载。然后我会制作一个通用数据包来打包这两种可能的有效载荷:

enum PayloadType: String, Codable {
case location = "loc"
case synchronize = "syn"
}

protocol Payload: Codable {
var payloadType: PayloadType { get }
}

struct Location: Payload {
let lat: Double
let long: Double
let accuracy: Double
let payloadType = PayloadType.location

enum CodingKeys: String, CodingKey {
case lat,long,accuracy
}
}

struct Synchronization: Payload {
let time: Int
let tz: String
let system: Int
let payloadType = PayloadType.synchronize

enum CodingKeys: String, CodingKey {
case time, tz, system
}
}

struct Packet<T: Payload>: Codable {
let data: T
let header: PayloadType

init(payload: T) {
data = payload
header = payload.payloadType
}
}

然后你可以这样做:

let location = Location(lat: 36.16, long: 50.36, accuracy: 5)
let packet = Packet(payload: location)

let json = try! encoder.encode(packet)

导致:

{
"data" : {
"lat" : 36.159999999999997,
"long" : 50.359999999999999,
"accuracy" : 5
},
"header" : "loc"
}

let location = Synchronization(time: 15646565455, tz: "+2", system: 5)
let packet = Packet(payload: location)

let json = try! encoder.encode(packet)

导致:

{
"data" : {
"system" : 5,
"time" : 15646565455,
"tz" : "+2"
},
"header" : "syn"
}

关于具有多种结构的 JSONEncoder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47931129/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com