[英]How to create JSON format from Realm “Results” using Object Mapper
I try to create JSON format from Realm Results using Object Mapper. 我尝试使用Object Mapper从Realm Results创建JSON格式。 So, I created two generic methods to do that. 因此,我创建了两个通用方法来做到这一点。 Fisrt method create array form Results
and looks like that: Fisrt方法创建数组形式的Results
,如下所示:
var allRealmData: Results<Project>? // in this variable I save all Project Objects first
func makeAnArrayFromResults<T>(object: T.Type) -> [T]?{
var array = [T]()
guard let mainArray = allRealmData else { return nil }
for i in mainArray {
if let object = i as? T {
array.append(object)
}
}
return array
}
then I would like to use Object Mapper
to change this array to JSON Object, but when I try do it, I receive an error and don't know how can I resolve it. 那么我想使用Object Mapper
将此数组更改为JSON Object,但是当我尝试执行此操作时,我收到一个错误,并且不知道如何解决它。 My second method looks like that: 我的第二种方法如下所示:
func createJSON<T: Object>(object: T.Type){
let array = makeAnArrayFromResults(object)
let json = Mapper().toJSONString(array!, prettyPrint: true) //here error
}
error info: Cannot invoke "toJSONString" with an argument list of type"([T], prettyPrint: Bool)". 错误信息:无法使用类型为“([T],prettyPrint:Bool)”的参数列表调用“ toJSONString”。
Do you have any sugestions how can I create JSON from Result
in Realm? 您有任何建议如何从Realm中的Result
创建JSON吗?
Firstly, makeAnArrayFromResults<T>
is really just map
: 首先, makeAnArrayFromResults<T>
实际上只是map
:
let someRealmResults: Results<Project>?
...
let array = someRealmResults?.map { $0 } // => [Project]?
As far as the Object Mapper integration goes, it looks like you don't have a toJSONString
function defined that satisfies the first argument type constraints of [Person]
. 就Object Mapper集成而言,似乎您没有定义满足[Person]
的第一个参数类型约束的toJSONString
函数。
There's quite a bit of discussion in Object Mapper's issue tracker about interoperability with Realm that you may find useful: https://github.com/Hearst-DD/ObjectMapper/issues/475 在Object Mapper的问题跟踪器中有很多关于与Realm互操作性的讨论,您可能会发现它有用: https : //github.com/Hearst-DD/ObjectMapper/issues/475
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.