- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想获取以下词典的 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/
我想将新数据添加到Mappable class。这是我的类: import Foundation import ObjectMapper struct AllcategoriesModel : Map
我想为下面的数据框创建一个散点图: df_sample.head(10) duration distance speed 0 26.299999 3.569 8.1 1 6.
我想为下面的数据框创建一个散点图: df_sample.head(10) duration distance speed 0 26.299999 3.569 8.1 1 6.
我正在使用 ObjectMapper library将我的模型对象(类和结构)与 JSON 相互转换。 但有时我想创建没有 JSON 的对象。 假设,我有这样的类(class): class User
我对 Swift 还很陌生,所以请耐心等待。我正在尝试使用 ObjectMapper 将 Swift 对象转换为 JSON 字符串。 我尝试将我的对象与 Mappable 接口(interface)一
我想获取以下词典的 json 字符串,但我不知道正确的方法是什么。 /* For example, I have a Dictionary contains a set of users and I
我正在为文本解码类编写一组单元测试。我想编写一个测试,正确执行将不可映射的 input 处理为 CharsetDecoder。但是,我很难启动一个执行此操作的字节缓冲区。示例: CharsetDeco
我看到以下示例同时绘制图像和颜色图: 代码: imgplot = plt.imshow(lum_img) plt.colorbar() 来自这里:http://matplotlib.org/users
我遇到了一些问题。服务器收到请求,但未正确处理映射。我不明白我做错了什么。 日志: 2016-04-25 19:39:16.114 cifrosvit[1063:15363] I restki
我有一个 NSObject 类型的 BaseRequestObject,Mappable 由一个名为 User 的对象继承。我需要将这个用户对象保存在 realmDB 中。 class BaseReq
当使用 RKMappingTest 对 RestKit 映射代码执行单元测试时,它们会失败并出现以下异常: 映射操作失败:给定 nil 目标对象,无法实例化映射的目标对象。 或(当目标对象被传递到 R
在我的 Realm 对象模型中,我有一个名为“事件”的对象。每个事件都有一个事件位置列表。我正在尝试从 json 映射这些对象,但 EventLocations 列表始终为空。对象看起来像这样(为清楚
我是一名优秀的程序员,十分优秀!