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)
}
}
答案 0 :(得分:0)
是的,您可以将它们存储在一个数组中,但如果您为struct
类型定义class
或Patient
,则使用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。