【发布时间】:2015-07-09 10:44:45
【问题描述】:
有没有办法将 PFObject 从 Parse 转换为 JSON?我保存为 JSON,但是当我尝试加载时,我得到了 [AnyObject]。转换为 JSON 不起作用:
class func loadPeople() -> [String : Person] {
var peopleDictionary: [String : Person] = [:]
let query = PFQuery(className: "userPeeps")
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil {
//this only returns the first entry, how do I get them all?
if let peopleFromParse = objects?.first?.objectForKey("userPeeps") as? JSON {
for name in peopleFromParse.keys {
if let personJSON = peopleFromParse[name] as? JSON,
let person = Person(json: personJSON) {
peopleDictionary[name] = person
}
}
}
下面是我的保存功能,它可以像我想要的那样工作并将 JSON 保存到 Parse 中:
class DataManager {
typealias JSON = [String: AnyObject]
class func savePeople(people: [String : Person]) {
var peopleDictionary = people
var peopleJSON: JSON = [:]
for name in peopleDictionary.keys {
peopleJSON[name] = peopleDictionary[name]!.toJSON()
}
let userPeeps = PFObject(className: "userPeeps")
userPeeps.setObject(peopleJSON, forKey: "userPeeps")
userPeeps.saveInBackgroundWithBlock { (succeeded, error) -> Void in
if succeeded {
println("Object Uploaded")
} else {
println("Error: \(error) \(error!.userInfo!)")
}
}
}
【问题讨论】:
-
你有几个问题。首先,您的 objectID 不会是“userpeeps” - 当一个新对象保存到 Parse 时,该 ID 是随机分配的。其次,您的 JSON 字符串被保存到 PFObject 中的“userPeeps”字段中,因此您需要检索字符串值并将其转换为 JSON 对象 - 您不能只转换它。
-
谢谢我更新了我的问题...我不知道如何获取所有值?这只是返回第一个
-
objects是一个 PFObject 数组。你需要遍历数组。 -
谢谢我的想法...谢谢!
标签: ios swift parse-platform