保存 JSON 中的数组到用户默认设置中,并读取数组值。

huangapple go评论109阅读模式
英文:

Save array from JSON in user default and read array values back

问题

I'm retrieving a JSON dict with the following structure:

"SITES": [
	{
  	"NAME": “ALICE LANE”,
  	"WEBSITEAPPID": “XYZ”
	}
  ]
}

I'm saving that straight into user defaults like this:

UserDefaults.standard.set(JSON(dict as Any)["SITES"].stringValue, forKey: "adminSites")

I know there is data in the JSON because the below code provides two rows of array data:

if let arraySites = dict?["SITES"] as? [[String: Any]] {
  for sitesDetails in arraySites {
    print(sitesDetails["NAME"] as Any)
    print(sitesDetails["WEBSITEAPPID"] as Any)
  }
}

When I try to print the user default data count, I get 0:

let defaultAdminSites = defaults.object(forKey: "adminSites") as? [String] ?? [String]()
print(defaultAdminSites.count)

Why am I getting 0 results? How would I get the array row details if I did for ["NAME"] and ["WEBSITEAPPID"]?

英文:

I'm retrieving a JSON dict with the following structure:

"SITES": [
	{
  	"NAME": “ALICE LANE”,
  	"WEBSITEAPPID": “XYZ”
	}
  ]
}

I'm saving that straight into user defaults like this:

UserDefaults.standard.set(JSON(dict as Any)["SITES"].stringValue, forKey: "adminSites")

I know there is data in the JSON because the below code provides two rows of array data:

if let arraySites = dict?["SITES"] as? [[String: Any]] {
  for sitesDetails in arraySites {
    print(sitesDetails["NAME"] as Any)
    print(sitesDetails["WEBSITEAPPID"] as Any)
  }
}

When I try print the user default data count, I get 0

let defaultAdminSites = defaults.object(forKey: "adminSites") as? [String] ?? [String]()
print(defaultAdminSites.count)

Why am I getting 0 results? How would get the array row details if I did for ["NAME"] and ["WEBSITEAPPID"]?

答案1

得分: 3

以下是翻译好的部分:

我建议使用一个模型对象和 `Codable` 来避免所有这些强制转换:

struct Model: Codable {
    let sites: [Site]

    enum CodingKeys: String, CodingKey {
        case sites = "SITES"
    }
}

struct Site: Codable {
    let name, websiteAppid: String

    enum CodingKeys: String, CodingKey {
        case name = "NAME"
        case websiteAppid = "WEBSITEAPPID"
    }
}

// 写入到用户默认设置
let model = Model(sites: [Site(name: "foo", websiteAppid: "bar")])
do {
    let siteData = try JSONEncoder().encode(model)
    UserDefaults.standard.set(siteData, forKey: "adminSites")
} catch {
    print(error)
}

// 从用户默认设置读取
if let siteData = UserDefaults.standard.data(forKey: "adminSites") {
    do {
        let model = try JSONDecoder().decode(Model.self, from: siteData)
        for site in model.sites {
            print(site.name, site.websiteAppid)
        }
    } catch {
        print(error)
    }
}

这是您提供的代码的翻译部分,没有其他内容。

英文:

I would recommend using a model object and Codable to avoid all those casts:

struct Model: Codable {
    let sites: [Site]

    enum CodingKeys: String, CodingKey {
        case sites = "SITES"
    }
}

struct Site: Codable {
    let name, websiteAppid: String

    enum CodingKeys: String, CodingKey {
        case name = "NAME"
        case websiteAppid = "WEBSITEAPPID"
    }
}

// write to defaults
let model = Model(sites: [Site(name: "foo", websiteAppid: "bar")])
do {
    let siteData = try JSONEncoder().encode(model)
    UserDefaults.standard.set(siteData, forKey: "adminSites")
} catch {
    print(error)
}

// read from defaults
if let siteData = UserDefaults.standard.data(forKey: "adminSites") {
    do {
        let model = try JSONDecoder().decode(Model.self, from: siteData)
        for site in model.sites {
            print(site.name, site.websiteAppid)
        }
    } catch {
        print(error)
    }
}

答案2

得分: -1

UserDefault 保存 Json 响应

let result = jsonDict["SITES"] as? NSArray ?? []

let data = try! NSKeyedArchiver.archivedData(withRootObject: result, requiringSecureCoding: false)
UserDefaults.standard.set(data, forKey: "adminSites")

获取 UserDefault 数据

let result = UserDefaults.standard.data(forKey: "adminSites")
if result != nil {
    let data = try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(result!) as? NSArray ?? []
    print("Current User Details: - \(data)")
}
英文:

UserDefault Save Json Response

let result = jsonDict["SITES"] as? NSArray ?? []

let data = try! NSKeyedArchiver.archivedData(withRootObject: result, requiringSecureCoding: false)
UserDefaults.standard.set(data, forKey: "adminSites")

Get UserDefault data

let result = UserDefaults.standard.data(forKey: "adminSites")
    if result != nil{
      let data = try! NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(result!) as? NSArray ?? []
      print("Current User Details : - \(data)")
}

huangapple
  • 本文由 发表于 2020年1月3日 17:10:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/59575754.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定