gpt4 book ai didi

ios - Reduce 或 Flatmap json 对单个数组的响应

转载 作者:行者123 更新时间:2023-11-28 05:44:25 24 4
gpt4 key购买 nike

我有一个 json 消息响应正文,如下所示。就我的 UI 而言,顶级消息只是列表中的第一条消息。

{
"messageId": "1234-1234-1234",
"jobId": "1234-1234-1234",
"message": "This is the top level message",
"createdDate": "2019-03-18T14:55:21.467",
"user": {},
"messages": [{
"messageId": "1234-1234-1234",
"jobId": "1234-1234-1234",
"message": "This is the a child message",
"createdDate": "2019-03-18T14:55:21.467",
"user": {},
"messages": [],
"attachments": []
},
{
"messageId": "1234-1234-1234",
"jobId": "1234-1234-1234",
"message": "This is the another child message",
"createdDate": "2019-03-18T14:55:21.467",
"user": {},
"messages": [],
"attachments": []
},
{
"messageId": "1234-1234-1234",
"jobId": "1234-1234-1234",
"message": "This is the yet another child message",
"createdDate": "2019-03-18T14:55:21.467",
"user": {},
"messages": [],
"attachments": []
}
],
"attachments": []
}

服务器实体

struct MessageServer: Codable {
let messageId: String
let jobId: String
let message: String
let createdDate: Date
let user: User
let messages: [MessageServer]
let attachments: [FileServer]

init(messageId: String,
jobId: String,
message: String,
createdDate: Date,
user: User,
messages: [MessageServer],
attachments: [FileServer]
) {

self.messageId = messageId
self.jobId = jobId
self.message = message
self.createdDate = createdDate
self.user = user
self.messages = messages
self.attachments = attachments
}

应用实体

struct Message: Codable {
let message: String
let createdDate: Date
let displayName: String
let isMine: Bool
let attachments: [File]

init(message: String, createdDate: Date, displayName: String, isMine: Bool, attachments: [File]) {
self.message = message
self.createdDate = createdDate
self.displayName = displayName
self.isMine = isMine
self.attachments = attachments
}

在我的服务调用中,我只想返回一个 Observable 消息数组。

func getMessages(sectionID id: String) -> Observable<[Message]> {
return messageServiceEndpoints
.getMessages(for: id)
.map({
$0.map({
Message( /* init message here */ )
})
})
}

有没有办法将其缩减或平面化为单个数组?

最佳答案

这不是真正的 RxSwift 问题...您只需要解析 JSON:

struct Message: Decodable {
let messageId: String
let message: String
let createdDate: Date
private (set) var messages: [Message]
// and the rest...

var droppedMessages: Message {
var result = self
result.messages = []
return self
}
}

func parseMessages(from data: Data) throws -> [Message] {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyy-MM-dd'T'HH:mm:ss.SSS"
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(dateFormatter)
let response = try decoder.decode(Message.self, from: data)
return [response.droppedMessages] + response.messages
}

关于ios - Reduce 或 Flatmap json 对单个数组的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55431462/

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