Item
배열을 초기화하려고합니다.
json 파일에서 s. 이를 위해, 나는 그것을 수행하는 애플의 튜토리얼을 따라 갔다 : 알고리즘은 data.swift에 있지만 요약 된 버전도 게시 할 것입니다.) 내 문제는 데이터를 가져 오는 API에서 따옴표로 소수점 이하 자릿수를 표시하여 오류가 발생한다는 것입니다.
Apple의 json 디코더가 기대하는 것 :
typeMismatch(Swift.Double, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "average_cost", intValue: nil)], debugDescription: "Expected to decode Double but found a string/data instead.", underlyingError: nil))
[{
"company": "Bioseed",
"item_class": "Seeds",
"name": "9909",
"stock": 0,
"average_cost": 0.00, // Doubles without quotation marks
"otc_price": 0.00,
"dealer_price": 0.00,
"ctc_price": 0.00
}]
에 저장된 API의 샘플 데이터
:
items.json
따옴표없이 소수점과 정수를 제공하도록 API를 다시 작성할 수는 있지만 다른 응용 프로그램에서 이미 사용 중이므로 무언가를 깨뜨릴 위험이 없습니다.
따라서 해독 된 사람에게 따옴표를 무시하도록 지시하는 방법이 있습니까?
항목 구조 :
[{
"company": "Bioseed",
"item_class": "Seeds",
"name": "9909",
"stock": 0,
"average_cost": "0.00",
"otc_price": "0.00",
"dealer_price": "0.00",
"ctc_price": "0.00"
}]
로드 기능 :
struct Item : Decodable {
var company: String
var item_class: String
var name: String
var stock: Int
var average_cost: Decimal
var otc_price: Decimal
var dealer_price: Decimal
var ctc_price: Decimal
전화 :
func load<T: Decodable>(_ filename: String, as type: T.Type = T.self) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}
let items: [Item] = load("items.json")
print(items)
- 답변 # 1
- OpenCv의 폴더에서 여러 이미지 읽기 (python)
- 파이썬 셀레늄 모든 "href"속성 가져 오기
- html - 자바 스크립트 - 클릭 후 변경 버튼 텍스트 변경
- javascript - 현재 URL에서 특정 div 만 새로 고침/새로 고침
- JSP에 대한 클래스를 컴파일 할 수 없습니다
- JavaScript 변수를 HTML div에 '출력'하는 방법
- git commit - 자식 - 로컬 커밋 된 파일에 대한 변경을 취소하는 방법
- jquery - JavaScript로 현재 세션 값을 얻으시겠습니까?
- javascript - swiperjs에서 정지, 재생 버튼 추가
- python - 화면에서 찾은 요소를 찾을 수없는 경우 셀레늄
이것을 구현하는 방법은 다음과 같습니다.
또는 모델에 문자열 속성을 유지하고 액세스시 소수로 변환 할 수 있습니다