swift 中字符串的对象列表
List of object to string in 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"}
data
是一个简单的字符串数组,也是一个有效的 json 对象。
但是 data2
是 Codable
的数组。默认情况下还不是有效的 json 对象。您需要首先将您的 data2: [NotificationModel]
转换为 data2Json: [[String:Any]]
以使其成为有效对象,然后将其传递给您的 json(from object
函数。您应该使用 JSONEncoder
将 [NotificationModel]
编码为有效的 json 对象。
您需要确保您尝试编码的内容符合 Encodable 协议。您可以使用 Foundation 的 JSONEncoder
加上一点泛型来确保 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))")
我想将对象列表转换为字符串以调用我的 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"}
data
是一个简单的字符串数组,也是一个有效的 json 对象。
但是 data2
是 Codable
的数组。默认情况下还不是有效的 json 对象。您需要首先将您的 data2: [NotificationModel]
转换为 data2Json: [[String:Any]]
以使其成为有效对象,然后将其传递给您的 json(from object
函数。您应该使用 JSONEncoder
将 [NotificationModel]
编码为有效的 json 对象。
您需要确保您尝试编码的内容符合 Encodable 协议。您可以使用 Foundation 的 JSONEncoder
加上一点泛型来确保 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))")