简体   繁体   中英

Save json in userDefaults

This is the set function

func setSelectedDivisions(_ division:[Division]) {

    if (division.count != 0) {
        self.userDefaults.set(division.toJSONString(), forKey: "selectedDivisions")
        self.userDefaults.synchronize()
    }
    else{
        self.userDefaults.removeObject(forKey: "selectedDivisions")
        self.userDefaults.synchronize()
    }
}

and this is the get function

func getSelectedDivisions() -> [Division] {

    if let json = self.userDefaults.value(forKey: "selectedDivisions"){
        print(json)
    }

    if let json = self.userDefaults.value(forKey: "selectedDivisions") as? Array<Dictionary<String, Any>>  {
        if  json.count != 0{
            let  divisions = Mapper<Division>().mapArray(JSONArray: json)
            if divisions.count != 0{
                return divisions
            }
        }
    }
    return []
}

in get function i got error told me that my serialization is wrong. this is the json i trying to get it

[{"name":"أ","img":"http://www.smsalmaali.com/images/cclass/21.jpg","name2":"الصف الاول","id1":"21","id2":"1"}]

any idea to fix it ?

i think this line of code is wrong

if let json = self.userDefaults.value(forKey: "selectedDivisions") as? Array<Dictionary<String, Any>> 

first you need to convert json string into array object , like follows

let data = (self.userDefaults.value(forKey: "selectedDivisions") as! String).data(using: String.Encoding.utf8) as NSData?
        if data == nil || data!.length == 0 {
            return 
        } else {
            do {
                let resultJSON = try JSONSerialization.jsonObject(with: data! as Data, options: .mutableContainers)
                if let json = resultJSON as? Array<Dictionary<String, Any>>  {
                  // do something
               }
        } catch _ {
          print("exception ")
      }

Using SwiftyJSON is really simple

Xcode 8+, Swift 3x

func saveJSON(json: JSON) {
    UserDefaults.standard.setValue(j.rawString()!, forKey: "YOUR_KEY")
}

func getJSON() -> JSON {
    return JSON.parse(UserDefaults.standard.value(forKey: "YOUR_KEY") as! String)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM