无法将类型“[JSON]”的值分配给类型“[MyStruct]”
Cannot assign value of type '[JSON]' to type '[MyStruct]'
我正在学习使用 SwiftyJSON,我正在尝试将结果值转换为 MyStruct 数组。但是,每当我尝试这样做时,它都会告诉我它们不兼容。如何将 [JSON] 转换为 [MyStruct]?
class TreatmentsManager: ObservableObject {
@Published var treatments = [Treatment]()
func testAlamofire() {
AF.request("http://dermaservice.theappmaster.com/Tratamiento.ashx").response { response in
switch response.result {
case .success(let value):
let json = JSON(value)
if let treatmentArray = json["Tratamientos"].array {
self.treatments = treatmentArray
//[MyStruct] type /= [JSON] type
}
case .failure(let error):
print(error)
}}}}
感谢@VishalPatel,我找到了解决方法:
class TreatmentsManager: ObservableObject {
@Published var treatments = [Treatment]()
func testAlamofire() {
AF.request("http://dermaservice.theappmaster.com/Tratamiento.ashx").response { response in
switch response.result {
case .success(let value):
do {
let results = try JSONDecoder().decode(TreatmentList.self, from: value!)
DispatchQueue.main.async {
self.treatments = results.Tratamientos
}
} catch {
print(error)
}
case .failure(let error):
print(error)
}
}
}
}
其中 TreatmentList 是一个包含 [Treatments] 的结构。
所以不需要使用 SwiftyJSON
我正在学习使用 SwiftyJSON,我正在尝试将结果值转换为 MyStruct 数组。但是,每当我尝试这样做时,它都会告诉我它们不兼容。如何将 [JSON] 转换为 [MyStruct]?
class TreatmentsManager: ObservableObject {
@Published var treatments = [Treatment]()
func testAlamofire() {
AF.request("http://dermaservice.theappmaster.com/Tratamiento.ashx").response { response in
switch response.result {
case .success(let value):
let json = JSON(value)
if let treatmentArray = json["Tratamientos"].array {
self.treatments = treatmentArray
//[MyStruct] type /= [JSON] type
}
case .failure(let error):
print(error)
}}}}
感谢@VishalPatel,我找到了解决方法:
class TreatmentsManager: ObservableObject {
@Published var treatments = [Treatment]()
func testAlamofire() {
AF.request("http://dermaservice.theappmaster.com/Tratamiento.ashx").response { response in
switch response.result {
case .success(let value):
do {
let results = try JSONDecoder().decode(TreatmentList.self, from: value!)
DispatchQueue.main.async {
self.treatments = results.Tratamientos
}
} catch {
print(error)
}
case .failure(let error):
print(error)
}
}
}
}
其中 TreatmentList 是一个包含 [Treatments] 的结构。 所以不需要使用 SwiftyJSON