首页 > 解决方案 > 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"} 

标签: iosswiftswift5

解决方案


您需要确保您尝试编码的内容符合 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))")

推荐阅读