英文:
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)")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论