gpt4 book ai didi

json - swift 对象映射器 : toJSONString for a dictonary containing mappable Object

转载 作者:行者123 更新时间:2023-11-30 12:32:26 28 4
gpt4 key购买 nike

我想获取以下词典的 json 字符串,但我不知道正确的方法是什么。

/* For example, I have a Dictionary contains a set of users and I want to get the JSONString of it. */

class User: Mappable {
// some other implemenation ...
}

/* in some other class, e.g MyService.swift */
func generateString() -> String {
let user1 = User()
let user2 = User()

// some other implemenation ...

let seatDict: [String:User] = [
"1A": user1,
"1B": user2,
// some other implemenation ...
// some other implemenation ...
]

// here i would like to return the JsonString of my seatDict
let result: String = ... // how to do it?
return result
}

最佳答案

您可以使用 Mapper 类来完成此操作。

...
// here i would like to return the JsonString of my seatDict
let jsonDict = Mapper<User>().toJSONDictionary(seatDict)
let result: String? = Mapper<User>.toJSONString(jsonDict as Any, prettyPrint: false)
return result

请记住,如果序列化失败,toJSONString 可能会返回 nil - 因此您需要在应用程序中以某种方式处理该问题。这就是为什么我将结果更改为可选

关于json - swift 对象映射器 : toJSONString for a dictonary containing mappable Object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43340481/

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