[英]Parsing JSON in Swift with nil values
I'm using Swift 5 and Xcode 11. I am attempting to parse the JSON coming back from this website, an API I am designing. I'm using Swift 5 and Xcode 11. I am attempting to parse the JSON coming back from this website, an API I am designing. http://aarontcraig-001-site1.htempurl.com/api/values
http://aarontcraig-001-site1.htempurl.com/api/values
The JSON returned from that API call is this:从 API 调用返回的 JSON 是这样的:
[
{
"Businesses": [],
"Customer": null,
"ID": 1,
"Name": "Coffee Shop",
"CustomerID": null
},
...
]
It continues an array.它继续一个数组。 Some of the entries are null, others are not.
有些条目是 null,有些则不是。 However, when I parse it, they all come back nil.
但是,当我解析它时,它们都返回为零。
Here is my code:这是我的代码:
let url = "http://aarontcraig-001-site1.htempurl.com/api/values"
guard let finalURL = URL(string: url) else {
return
}
URLSession.shared.dataTask(with: finalURL) { (data, response, error) in
guard let data = data else {return}
do {
let myData = try JSONDecoder().decode([Value].self, from: data)
print(myData)
}
catch {
print("Error parsing \(error)")
}
and the struct I am using to catch it all:以及我用来捕捉这一切的结构:
struct Value: Codable {
let businesses : [String]?
let customer : String?
let iD : Int?
let name : String?
let customerID : String?
}
All I get back is nil values, even though clearly many of them aren't.我得到的只是 nil 值,尽管其中很多显然不是。 This is what it returns.
这就是它返回的内容。
[Sunrise.Value(businesses: nil, customer: nil, iD: nil, name: nil, customerID: nil), Sunrise.Value(businesses: nil, customer: nil, iD: nil, name: nil, customerID: nil), Sunrise.Value(businesses: nil, customer: nil, iD: nil, name: nil, customerID: nil), Sunrise.Value(businesses: nil, customer: nil, iD: nil, name: nil, customerID: nil), Sunrise.Value(businesses: nil, customer: nil, iD: nil, name: nil, customerID: nil), Sunrise.Value(businesses: nil, customer: nil, iD: nil, name: nil, customerID: nil)] [Sunrise.Value(企业:无,客户:无,ID:无,名称:无,客户ID:无),Sunrise.Value(企业:无,客户:无,ID:无,名称:无,客户ID:无) ,Sunrise.Value(企业:无,客户:无,ID:无,名称:无,客户ID:无),Sunrise.Value(企业:无,客户:无,ID:无,名称:无,客户ID:无) ,Sunrise.Value(企业:无,客户:无,ID:无,名称:无,客户ID:无),Sunrise.Value(企业:无,客户:无,ID:无,名称:无,客户ID:无) ]
What am I doing wrong?我究竟做错了什么? Even if I attempt to just capture name which has a value for each entry, it sets it to nil.
即使我尝试仅捕获每个条目都有值的名称,它也会将其设置为 nil。 I am receiving the data, because if I put a breakpoint at data I can see it there.
我正在接收数据,因为如果我在数据处设置断点,我可以在那里看到它。
Map the property names from the JSON to your struct's members using CodingKeys
: Map 使用
CodingKeys
从 JSON 到结构成员的属性名称:
struct Value: Codable {
let businesses: [String]?
let customer: String?
let id: Int
let name: String
let customerID: String?
enum CodingKeys: String, CodingKey {
case businesses = "Businesses"
case customer = "Customer"
case id = "ID"
case name = "Name"
case customerID = "CustomerID"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.