신속한 코딩 가능 사전
Sep 10 2020
코드화하는 데 문제가 있습니다. 어떤 도움이라도 대단히 감사하겠습니다. 내 놀이터에 다음이 있습니다.
내 JSON 파일의 샘플. 더 많은 요소가 있으며 더 작은 하위 집합으로 축소되었습니다.
{
"metadata" : {
"generated" : {
"timestamp" : 1549331723,
"date" : "2019-02-04 20:55:23"
}
},
"data" : {
"CA" : {
"country-id" : 25000,
"country-iso" : "CA",
"country-eng" : "Canada",
"country-fra" : "Canada",
"date-published" : {
"timestamp" : 1544561785,
"date" : "2018-12-11 15:56:25",
"asp" : "2018-12-11T15:56:25.4141468-05:00"
}
},
"BM" : {
"country-id" : 31000,
"country-iso" : "BM",
"country-eng" : "Bermuda",
"country-fra" : "Bermudes",
"date-published" : {
"timestamp" : 1547226095,
"date" : "2019-01-11 12:01:35",
"asp" : "2019-01-11T12:01:35.4748399-05:00"
}
}
}
}
Quicktype 앱에서. 데이텀 사전을 생성했습니다. json이 구조화되는 방식에 따라 국가 약어에는 태그가 없습니다.
import Foundation
// MARK: - Welcome
struct Welcome: Codable {
let metadata: Metadata?
let data: [String: Datum]?
}
// MARK: - Datum
struct Datum: Codable {
let countryID: Int?
let countryISO, countryEng, countryFra: String?
let datePublished: DatePublished?
enum CodingKeys: String, CodingKey {
case countryID = "country-id"
case countryISO = "country-iso"
case countryEng = "country-eng"
case countryFra = "country-fra"
case datePublished = "date-published"
}
}
// MARK: - DatePublished
struct DatePublished: Codable {
var timestamp: Int
var date, asp: String
}
// MARK: - Metadata
struct Metadata: Codable {
var generated: Generated
}
// MARK: - Generated
struct Generated: Codable {
var timestamp: Int
var date: String
}
// MARK: - Encode/decode helpers
class JSONNull: Codable, Hashable {
public static func == (lhs: JSONNull, rhs: JSONNull) -> Bool {
return true
}
public var hashValue: Int {
return 0
}
public func hash(into hasher: inout Hasher) {
// No-op
}
public init() {}
public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if !container.decodeNil() {
throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}
내 코드에서 json 파일을로드 할 수 있습니다. 여기에서 사전을 사용하여 데이터를 처리하는 방법을 잘 모르겠습니다. 국가에는 국가 약어 이름이 없습니다.
guard let url = Bundle.main.url(forResource: "data", withExtension: "json") else { return 0 }
let jsonData = try Data(contentsOf: url)
참고 : 이것은 이전 질문에 대한 후속 조치입니다. Swift Codable Parsing keyNotFound
답변
1 DávidPásztor Sep 09 2020 at 23:41
데이터 모델이 이미 올바르게 정의되어 있습니다 (하지만 이름을 변경하고 속성에서 변경 / 선택 사항을 제거하는 것이 좋습니다).
JSON을 파싱 한 후에 Dictionary는 키가 실제로 country-iso키 아래 값의 일부이기 때문에을 유지할 필요가 없습니다 .
그래서 일단 당신이 당신의 Root객체 를 해독했다면 , 나는 당신이 나중에 쉽게 다룰 수있는 당신 root.data.values에게주는 단순히를 유지하는 것을 제안 할 것 Array<CountryData>입니다.
struct Root: Codable {
let data: [String: CountryData]
}
struct CountryData: Codable {
let countryID: Int
let countryISO, countryEng, countryFra: String
let datePublished: DatePublished
enum CodingKeys: String, CodingKey {
case countryID = "country-id"
case countryISO = "country-iso"
case countryEng = "country-eng"
case countryFra = "country-fra"
case datePublished = "date-published"
}
}
// MARK: - DatePublished
struct DatePublished: Codable {
let timestamp: Int
let date, asp: String
}
do {
let root = try JSONDecoder().decode(Root.self, from: countryJson.data(using: .utf8)!)
let countries = root.data.values
print(countries)
} catch {
error
}