我正在制作一个需要接受JSON响应的手表套件/ Apple Watch应用程序,问题是“普通” JSON看起来像这样:
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
我尝试使用的JSON看起来像这样:
{
flag: false,
abuses: null,
recoubs_by_users_channels: [ ],
favourite: true,
recoub: false,
like: false,
dislike: false,
in_my_best2015: false,
id: 72838304,
type: "Coub::Simple",
permalink: "16xwc3",
...
我测试了我在下面编写的func,它在顶部JSON上可以100%起作用,而在底部JSON上却不能! (我怀疑缺少""
符号可能会导致此问题)
JSON结构:
struct Test: Decodable {
let flag: Bool
let favourite: Bool
let title: String
}
JSON提取功能:
func fetchJSON() {
let jsonUrlString = "https://coub.com/api/v2/coubs/16xwc3"
guard let url = URL(string: jsonUrlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, err) in
DispatchQueue.main.async {
if let err = err {
print("Failed to get data from URL:", err)
return
}
guard let data = data else { return }
do {
let decoder = JSONDecoder()
// decoder.keyDecodingStrategy = .convertFromSnakeCase
let course = try decoder.decode(Test.self, from: data)
self.label1.setText("Flag: \(course.flag)")
self.label2.setText("Favourite: \(course.favourite)")
self.label2.setText("Title: \(course.title)")
} catch let jsonErr {
print("")
print("")
print("")
print("Failed to decode JSON:", jsonErr)
print("")
print("")
print("")
}
}
}.resume()
}
我想让这个功能与看起来像JSON的“怪异”一起工作(读取值)!