简体   繁体   English

将json保存在userDefaults中

[英]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 这是get函数

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. 在get函数中,我收到错误消息,告诉我我的序列化错误。 this is the json i trying to get it 这是我试图得到的json

[{"name":"أ","img":"http://www.smsalmaali.com/images/cclass/21.jpg","name2":"الصف الاول","id1":"21","id2":"1"}] [{“ 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 首先,您需要将json字符串转换为数组对象,如下所示

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 使用SwiftyJSON非常简单

Xcode 8+, Swift 3x 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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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