簡體   English   中英

在Swift中將PFObject(Parse)轉換成JSON?

[英]Converting PFObject (Parse) into JSON in Swift?

有沒有一種方法可以將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!)")
                        }
                    }

    }

因此,答案(如Paulw11所指出的)是“對象”有點像是對實際數據的包裝,因此有必要遍歷數組並將每個值存儲為JSON:

var peopleDictionary: [String : Person] = [:]

        //1 load the dictionary of JSON for key people from Parse
        let query = PFQuery(className: "userPeeps")

        query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
            if error == nil {

                if let unwrappedObjects = objects {

                    for object in unwrappedObjects {

                        if let peopleFromParse = object as? JSON {

                            for name in peopleFromParse.keys {
                                if let personJSON = peopleFromParse[name] as? JSON,

                                    let person = Person(json: personJSON) {
                                        peopleDictionary[name] = person
                                }
                            }
                        }
                    }
                }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM