Swift ObjectMapper:toJSONString,用于包含可映射对象的命令

Swift ObjectMapper:toJSONString,用于包含可映射对象的命令,json,swift,dictionary,Json,Swift,Dictionary,我想为下面的字典获取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

我想为下面的字典获取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
}

您可以使用
映射器
类来实现这一点

...
// 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
。。。
//在这里,我想返回SeatDisct的JsonString
让jsonDict=Mapper().toJSONDictionary(seatDict)
让结果:字符串?=toJSONString(jsonDict如有,预打印:false)
返回结果

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

如果我使用上述方法,我会得到一个json字符串,如
“{list:{1A:{…}”
,这不是我想要的。我想要一个字符串,如:
{1A:{…},1B:{…},{…}
我修改了答案,这就是你想要的吗?