如何在数组中保存多个json对象

时间:2016-11-21 03:06:18

标签: arrays json swift

嘿伙计们我有json对象。我想在数组中讲述许多json对象。我的意思是我想在json对象中保存患者信息。这是工作。但我无法在json对象中保存多个患者信息。我应该在数组中插入我的json对象吗?

    let jsonData = try! JSONSerialization.data(withJSONObject: para, options: JSONSerialization.WritingOptions.init(rawValue: 0))

    jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue) as! String

    print(jsonString)

    do {
        let SavedPatient = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject]
        print("SavedPatient \(SavedPatient)")
        if let arrJSON = SavedPatient["contacts"] {
            for index in 0...arrJSON.count-1 {
                let aObject = arrJSON[index] as! [String : AnyObject]
                print("object in array \(aObject)")
            }
        }
    }
    catch {
        print(error)
    }

    let utf8str = jsonString.data(using: String.Encoding.utf8)
    if let base64Encoded = utf8str?.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
    {
        let encodedData = NSData(base64Encoded: base64Encoded, options:NSData.Base64DecodingOptions(rawValue:0))
        //let data = encodedData
        if encodedData != nil {
            //write
            encodedData?.write(toFile: "\(NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])/offline", atomically: true)

        }
    }

1 个答案:

答案 0 :(得分:0)

是的,您可以将它们存储在一个数组中,但如果您为struct类型定义classPatient,则使用JSON设置其属性会更加清晰数据,然后将Patient个对象存储在数组中。

例如,Patient结构:

struct Patient {
    var lastName: String?
    var firstName: String?
    // etc.
}

初始化一个数组来存储患者:

var patients = [Patient]()

然后,当您阅读每个JSON对象时,创建一个Patient

var lastName = aObject["lastName"]    // or whatever your JSON field is named
var firstName = aObject["firstName"]  // or whatever your JSON field is named
var patient = Patient(lastName: lastName, firstName: firstName /*, etc. */)

并将其粘贴在数组中:

patients.append(patient)

请注意,我将结构的属性声明为Optional s。