Sebastien Desemberg
Sebastien Desemberg

Reputation: 321

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 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"]?

Upvotes: 0

Views: 203

Answers (2)

Gereon
Gereon

Reputation: 17844

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)
    }
}

Upvotes: 3

Himanshu Patel
Himanshu Patel

Reputation: 1033

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)")
}

Upvotes: -1

Related Questions