Search code examples
iosswiftswift5

List of object to string in swift


I want to convert the list of objects to string for the call to my API?

It's working for data array. but got an error for data2 array

Error 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))")

Result should be looks like this

"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"} 

Solution

  • You need to ensure that the thing you're trying to Encode conforms to the Encodable protocol. You can use Foundation's JSONEncoder plus a litle bit of generics to ensure that the input to your json function is encodable, like this:

    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))")