ios - swift中要字符串的对象列表
问题描述
我想将对象列表转换为字符串以调用我的 API?
它适用于data
数组。data2
但数组出错
错误 terminating with uncaught exception of type NSException
let data = ["123","1234"]
let data2 = [NotificationModel(version: "2", bigPicture: "data"),
NotificationModel(version: "3", bigPicture: "data")]
struct NotificationModel: Codable {
var version : String?
var bigPicture : String?
}
func json(from object:Any) -> String? {
guard let data = try? JSONSerialization.data(withJSONObject: object, options: []) else {
return nil
}
return String(data: data, encoding: String.Encoding.utf8)
}
print("\(json(from:data2 as [NotificationModel]))")
print("\(json(from: data as Any))")
结果应该是这样的
"notifications":"[{\"body\":\"dfg\",\"groupKey\":\"bhanukacom072\",\"messageData\":\"{\\\"audioSeconds\\\":0,\\\"chatCount\\\":891,\\\"chatFieldId\\\":\\\"16184658508585169\\\",\\\"content\\\":\\\"dfg\\\",\\\"createdAt\\\":{\\\"_seconds\\\":1621765164,\\\"_nanoseconds\\\":964804000},\\\"fromUserId\\\":\\\"W6qfPNooEwhRU3xVlF3FZYdxGeZ2\\\",\\\"fromUserName\\\":\\\"bhanuka com 072\\\",\\\"isChat\\\":true,\\\"messageStatus\\\":\\\"U\\\",\\\"readStatus\\\":\\\"U\\\",\\\"requirementId\\\":\\\"671\\\",\\\"sendBy\\\":\\\"V\\\",\\\"timestamp\\\":1621765164964,\\\"toUserId\\\":\\\"TVhRuzRekqnPhhmb1oATXwc10En62\\\",\\\"toUserName\\\":\\\"bhanuka yc\\\",\\\"type\\\":\\\"text\\\",\\\"unReadMessageCount\\\":4,\\\"version\\\":2,\\\"docId\\\":\\\"eIfo9thTzyUmURMGX2uyj\\\"}\",\"title\":\"You have a message from bhanuka com 072\",\"version\":\"2\"}]","isVendor":false},"executionTime":0.008731000125408173,"log":"Initial response","endpoint":"createChat"}
解决方案
您需要确保您尝试编码的内容符合 Encodable 协议。您可以使用 FoundationJSONEncoder
加上一点泛型来确保json
函数的输入是可编码的,如下所示:
import Foundation
let data = ["123","1234"]
let data2 = [NotificationModel(version: "2", bigPicture: "data"),
NotificationModel(version: "3", bigPicture: "data")]
struct NotificationModel: Codable {
var version : String?
var bigPicture : String?
}
func json<T:Encodable>(from object:T) -> String? {
let encoder = JSONEncoder()
do {
let data = try encoder.encode(object)
return String(data: data, encoding: .utf8)
} catch {
return nil
}
}
print("\(json(from: data2))")
print("\(json(from: data))")
推荐阅读
- c++ - 如何使用 xdevapi 通过 C++ 代码登录 MySQL?
- regex - -replace 用它的名字替换 RegEx 组
- c# - Using Navigation property inside navigation property
- react-native - 在 react-native-maps 中,在 UrlTile 中反转 y 轴(用于支持 TMS)
- html-table - 表 TD 宽度未更新
- python - 无法连接到 python 中 requests.get() 或 requests.post() 上的代理错误
- python - Spark (2.2) 性能 <-> Spark Persist
- json - Spring & MongoDB - JSON 输出中的代理 DBRefs
- javascript - 如何检测在“选择”下拉列表中选择了哪个选项
- c# - 将多个子项添加到自定义控件的属性