ios - Swift 5: Decoding Nested JSON
问题描述
I'm having a little trouble decoding some JSON data into a struct. I've tried below methods and it doesn't work:
JSON:
{
"submission_date": "2020-02-28T14:21:46.000+08:00",
"status": "pending",
"requestor": {
"name": "Adam"
},
"claim_items": [
{
"date": "2020-02-20",
"description": "TV",
"currency": "MYR",
"amount": "103.0",
"amount_in_ringgit": "10.0"
},
{
"date": "2020-02-20",
"description": "Netflix",
"currency": "MYR",
"amount": "12.0",
"amount_in_ringgit": "10.0"
}
]
}
Struct Method 1:
struct ClaimDetail: Decodable {
let submission_date: String
let status: String
let requestor: Requestor
let claim_items: [ClaimItem]
}
struct Requestor: Decodable {
let name: String
init(json: [String:Any]) {
name = json["name"] as? String ?? ""
}
}
struct ClaimItem: Decodable {
let date: String
let description: String
let currency: String
let amount: String
let amount_in_ringgit: String
init(json: [String:Any]) {
date = json["date"] as? String ?? ""
description = json["description"] as? String ?? ""
currency = json["currency"] as? String ?? ""
amount = json["amount"] as? String ?? ""
amount_in_ringgit = json["amount_in_ringgit"] as? String ?? ""
}
}
Struct Method 2:
struct ClaimDetail: Decodable {
let submission_date: String
let status: String
let requestor: Requestor
let claim_items: [ClaimItem]
struct Requestor: Decodable {
let name: String
init(json: [String:Any]) {
name = json["name"] as? String ?? ""
}
}
struct ClaimItem: Decodable {
let date: String
let description: String
let currency: String
let amount: String
let amount_in_ringgit: String
init(json: [String:Any]) {
date = json["date"] as? String ?? ""
description = json["description"] as? String ?? ""
currency = json["currency"] as? String ?? ""
amount = json["amount"] as? String ?? ""
amount_in_ringgit = json["amount_in_ringgit"] as? String ?? ""
}
}
}
Struct Method 3 (via https://app.quicktype.io/):
// MARK: - ClaimDetail
struct ClaimDetail: Codable {
let submissionDate, status: String
let requestor: Requestor
let claimItems: [ClaimItem]
enum CodingKeys: String, CodingKey {
case submissionDate = "submission_date"
case status, requestor
case claimItems = "claim_items"
}
}
// MARK: - ClaimItem
struct ClaimItem: Codable {
let date, claimItemDescription, currency, amount: String
let amountInRinggit: String
enum CodingKeys: String, CodingKey {
case date
case claimItemDescription = "description"
case currency, amount
case amountInRinggit = "amount_in_ringgit"
}
}
// MARK: - Requestor
struct Requestor: Codable {
let name: String
}
URL Session
URLSession.shared.dataTask(with: requestAPI) { [weak self] (data, response, error) in
if let data = data {
do {
let json = try JSONDecoder().decode(ClaimDetail.self, from: data)
print (json)
} catch let error {
print("Localized Error: \(error.localizedDescription)")
print("Error: \(error)")
}
}
}.resume()
All returns below error:
Localized Error: The data couldn’t be read because it isn’t in the correct format.
Error: dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})))
解决方案
Solution:
I used struct method #1 and it wasn't the issue. The issue was with how I decoded the data in URLSession. For some reason, this works:
URLSession.shared.dataTask(with: requestAPI) { [weak self] (data, response, error) in
if let data = data {
do {
let dataString = String(data: data, encoding: .utf8)
let jsondata = dataString?.data(using: .utf8)
let result = try JSONDecoder().decode(ClaimDetail.self, from: jsondata!)
print(result)
} catch let error {
print("Localized Error: \(error.localizedDescription)")
print("Error: \(error)")
}
}
}.resume()
Screenshot:
I don't really understand but I guess I had to convert the data into a string, then decode that instead?
Thank you all for helping out.
推荐阅读
- javascript - 从另一个向量和一个旋转中计算出一个 3D 向量
- r - 基于相同的数据框添加第二个 y 轴
- google-sheets - 如何根据另一列的引用比较行?
- mysql - sql插入查询产生额外的记录
- php - codeigniter 学说 getRepository() 在本地工作但不在服务器上
- jquery - SVG 仅在具有隐私浏览的移动 Safari 中呈现
- xml - XML - 在文件路径中包含当前月份
- c# - Winforms DbContext Per Form
- google-cloud-platform - gcloud 数据存储模拟器:[Errno 8] 提供节点名或服务名,或未知
- c++ - 在 switch 块中使用 QVariant::Type 的用户类型的 GCC 警告