Swift ObjectMapper:包含可映射对象的dictonary的toJSONString

时间:2017-04-11 08:22:39

标签: json swift dictionary

我想获取以下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 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
}

1 个答案:

答案 0 :(得分:0)

您可以使用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,因此您需要在应用程序中以某种方式处理它。这就是我将result更改为可选

的原因