如何使用Swift从Nested Struct读取本地数据

时间:2019-05-07 16:26:03

标签: swift struct swift4

我正在使用以下函数保存和加载数据,并使用以下结构进行建模,但是我无法读取EntityDat数组,不确定是否是由于 EntityModel Struct 或加载数据中的调用(让entityData =尝试JSONDecoder()。decode(EntityModel.self,来自:loadedData))是不正确的。

我希望我的加载函数返回一个属于其父EntityModel的EntityData数组。 (例如下面)

 EntityModel {
   {
    "client_name": "John",
    "rut": "70.605.045-5",
    "segment": "Empresa"
   },
   {
    "client_name": "Alex",
    "rut": "60.345.234-1",
    "segment": "Pyme"
   },
   {
    "client_name": "Alice",
    "rut": "12.426.434-5",
    "segment": "Empresa"
   },
}

我收到的当前输出是: EntityData: EntityModel(entidad: nil)

保存功能:

func saveEntityToCoreData2()-> Bool {
        var SavedItem:Bool = true

        var mDictionary : [String: Any] = [
                "client_name": self.clientNameFromCore,
                "rut": self.clientRutFromCore,
                "segment": self.segmentFromCore ]

        let jsonData = try! JSONSerialization.data(withJSONObject: mDictionary, options: [.prettyPrinted])
        let json = String(data: jsonData, encoding: String.Encoding.utf8)!
        print("Saved Entity Dictionary", json)

        if self.saveRutSwitchOn
        {
            SecureData.save(key: "entityData", data: json.data(using: .utf8)!)
        }
        SavedItem = self.saveRutSwitchOn

        return SavedItem
    }

加载功能:

func loadEntityToCoreData2() {
        if let loadedData = SecureData.load(key: "entityData") {
            do {
                let entityData = try JSONDecoder().decode(EntityModel.self, from: loadedData)
                print("EntityData: ", entityData)
            } catch {
                print(error.localizedDescription)
            }
        }
    }

结构:

//Entity Model
struct EntityModel: Codable {
    let entidad: [EntityData]!
}

struct EntityData: Codable {
    let client_name: String!
    let rut: String!
    let segment: String!
}

1 个答案:

答案 0 :(得分:0)

更正json

[
   {
    "client_name": "John",
    "rut": "70.605.045-5",
    "segment": "Empresa"
   },
   {
    "client_name": "Alex",
    "rut": "60.345.234-1",
    "segment": "Pyme"
   },
   {
    "client_name": "Alice",
    "rut": "12.426.434-5",
    "segment": "Empresa"
   }
]


struct EntityModel: Codable {
  let clientName, rut, segment: String 
}

 let decoder = JSONDecoder()
 decoder.keyEncodingStrategy = .convertToSnakeCase
 let entityData = decoder.decode([EntityModel].self, from:data)

保存时,将其设置为类似的数组

var arr : [[String: Any]] = [[
            "client_name": self.clientNameFromCore,
            "rut": self.clientRutFromCore,
            "segment": self.segmentFromCore ]]