使用JSON从API获取数据的问题

时间:2019-06-01 14:55:45

标签: json swift api

我要从API获取数据,我正在使用JSON在表中查看数据。我可以访问数据,以字符串格式显示,但不能将其放在数组中。

这是我正在使用的代码:

struct Medicine : Decodable
{
let Code: String
let denomination:String
enum SerializationError: Error
    {
        case missing (String)
        case invalid(String, Any)
    }
    init(json:[String:Any]) throws
    {
    guard let Code = json["Code"] as?String
    else{throw SerializationError.missing("Code is missing")}
    guard let denomination = json["denomination"] as?String
    else{throw SerializationError.missing("denomination is missing")}
self.Code = Code
self.denomination = denomination
    }
}

func connectAPI (){
let url = "https://urlname"
let request = URLRequest(url: URL(string: url)!)
let task = URLSession.shared.dataTask(with: request)
{ (data:Data?, response:URLResponse?, error:Error?) in
    var queryArray  = [Medicine]()
            if let data = data
            {
do {queryArray = try JSONDecoder().decode([Medicine].self, from: data)}
                catch { print(error)}
            }
        }
}

这是我在浏览器中访问数据时的格式: 我希望有一个表2列:代码和面额

[ 
{
"code": "123",
"denomination": "demomination1"
  },
  {
"code": "456",
"denomination": "demomination2"
  }
]

1 个答案:

答案 0 :(得分:0)

您的代码不起作用,因为该对象是一个数组[[String:Any]],您必须根据该数组中的每个字典创建Medicine实例。

if let json = try JSONSerialization.jsonObject(with: data) as? [[String:Any]] {
   for item in json {
       if let medicine = try? Medicine(json: item) {
           queryArray.append(medicine)
       }
   }
}

但是我建议使用Decodable,它更易于使用且更有效

struct Medicine : Decodable {
    let code, denomination : String
}

var queryArray  = [Medicine]()

if let data = data {
do {
   queryArray = try JSONDecoder().decode([Medicine].self, from: data)             
} catch {
   print(error)
}