在swift中使用JSonJoy解析json并保存到modelClass中?

时间:2017-09-28 06:04:32

标签: swift3

这是我的json结构----->我应该如何使用JSONJoy保存在模型类中。 JSON:

Optional(<__NSSingleObjectArrayI 0x61000000b570>(
   {
    locationC = 116789;
    locationN = testrtyuio;
    siteName = lab;
   }
  )
 )

1 个答案:

答案 0 :(得分:0)

请检查:

struct LocationDetails: JSONJoy {
    var locationC: String? // based on your datatype change it
    let locationN: String? // based on your datatype change it
    let siteName: String? // based on your datatype change it
    init(_ decoder: JSONDecoder) throws {
        locationC = try decoder["locationC"].get()
        locationN = try decoder["locationN"].get()
        siteName = try decoder["siteName"].get()
    }
}

let data = try Data(contentsOf: file) // data is your json format
var locationDetails = try LocationDetails(JSONDecoder(data))
print(locationDetails) // Output : LocationDetails(locationC: Optional("116789"), locationN: Optional("testrtyuio"), siteName: Optional("lab"))
print(locationDetails.locationC!) // Output : 116789