简体   繁体   English

Swift ObjectMapper:toJSONString用于包含可映射对象的字典

[英]Swift ObjectMapper: toJSONString for a dictonary containing mappable Object

I would like to to get the json string for the following Dictionary, but I don't know what is the appropriate way to do so. 我想获取以下字典的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
}

You can do this by using the Mapper class. 您可以通过使用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

Keep in mind that toJSONString can return nil if serialisation fails - so you need to handle that somehow in your application. 请记住,如果序列化失败,则toJSONString可以返回toJSONString因此您需要以某种方式在应用程序中进行处理。 That's why I changed result to be optional 这就是为什么我将result更改为可选

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM