解析标签swift 4中的json数组

问题描述 投票:-1回答:2

这是我的JSON数组

[  
   {  
      "dollar":"15000",
      "date":"1397-12-12"
   }
]

我想在两个不同的标签中显示美元和日期值,但我有这种类型不匹配错误:

typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))

这是我的结构:

    struct Dollar_Date : Codable {
    let dollar : String
    let date : String
}

这是我在视图控制器中的代码:

func dollarLabel() {

let urlString = DOLLAR_DATE_BASE_URL
guard let url = URL(string: urlString) else { return }

// 2
URLSession.shared.dataTask(with: url) { (data, response, error) in
    if error != nil {
        print(error!.localizedDescription)
    }

    guard let data = data else { return }
    do {
        // 3
        //Decode data
        let JSONData = try JSONDecoder().decode(Dollar_Date.self, from: data)

        // 4
        print(JSONData.dollar)
        //Get back to the main queue
        DispatchQueue.main.async {
            self.main_Price.text = JSONData.dollar
            self.data_Label.text = JSONData.date
        }

    } catch let jsonError {
        print(jsonError)
    }
    // 5
    }.resume()

}

json parsing uilabel swift4.2
2个回答
0
投票

试试这个:

guard let jsonArray = JSONData as? [[String: Any]] else {
      return 
}
print(jsonArray)
//Now get title value 
guard let title = jsonArray[0]["title"] as? String else { return } print(title)

0
投票

您收到错误,因为您的数据包含JSON数组(字典也是如此),而不是JSON本身。

所以你无法解码

 let JSONData = try JSONDecoder().decode(Dollar_Date.self, from: data)

但你必须手动完成:

编辑:

guard let json = data as? [[String:Any]] else{return}

现在,您可以从数组的所有元素中检索美元和日期:

 // These are because you have to access an element of the array
 guard let dollar = json[0]["dollar"] as? String else {return}
 guard let date = json[0]["date"] as? String else {return}

 DispatchQueue.main.async {
        self.main_Price.text = dollar
        self.data_Label.text = date
    }

如果您的数据可以包含多个值(美元 - 日期对),您必须循环您的数组。通过前面的示例,您应该:

for element in json{
    guard let dollar = element["dollar"] as? String else {return}
    guard let date = element["date"] as? String else {return}

    // do some stuff with each value
}
© www.soinside.com 2019 - 2024. All rights reserved.