我想解析这个JSON
{"success":true,"timestamp":1523403184,"base":"EUR","date":"2018-04-11","rates":{"AED":4.540671,"AFN":86.176964,"ALL":128.832708,"AMD":595.029101,"ANG":2.200839,"AOA":267.813784,"ARS":24.89115,"AUD":1.592116,"AWG":2.200789,"AZN":2.101261,"BAM":1.958947,"BBD":2.472797}}
我使用了SwiftyJSONAccelator和程序给我2个文件。
//
// MoneyClass.swift
//
// Copyright (c) . All rights reserved.
//
import Foundation
import SwiftyJSON
public final class MoneyClass: NSCoding {
// MARK: Declaration for string constants to be used to decode and also serialize.
private struct SerializationKeys {
static let base = "base"
static let date = "date"
static let timestamp = "timestamp"
static let rates = "rates"
static let success = "success"
}
......
和第二个文件
//
// Rates.swift
//
// Copyright (c) . All rights reserved.
//
import Foundation
import SwiftyJSON
public final class Rates: NSCoding {
// MARK: Declaration for string constants to be used to decode and also serialize.
private struct SerializationKeys {
static let xAF = "XAF"
static let rON = "RON"
static let mYR = "MYR"
......
我想为表视图解析这个 JSON 文件。 但我不明白这怎么可能。 请帮助我。 有没有关于这个主题的教程? 感谢您的帮助。
这个问题说明了为什么如果情况与预期用途不匹配,使用好的工具有时会导致不良结果。为SerializationKeys
生成大写不佳的常量实际上看起来像代码气味,确实如此。了解Codable
协议确实值得,因为它是解决此问题的正确解决方案。你最终会得到这样的东西:
import Cocoa
struct Rates : Codable {
let success:Bool
let timestamp:Int
let base:String
let date:String
let rates:[String:Double]
}
let string = """
{
"success":true,
"timestamp":1523403184,
"base":"EUR",
"date":"2018-04-11",
"rates":{
"AED":4.540671,"AFN":86.176964,"ALL":128.832708,"AMD":595.029101,"ANG":2.200839,
"AOA":267.813784,"ARS":24.89115,"AUD":1.592116,"AWG":2.200789,"AZN":2.101261,
"BAM":1.958947,"BBD":2.472797
}
}
"""
let jsonData = string.data(using: .utf8)!
let decodr = JSONDecoder()
let result = try! decodr.decode(Rates.self, from: jsonData)
if result.success {
print("got (result.rates.count) rates from JSON")
print("Thre rate of AUD against (result.base) is (result.rates["AUD"]!)")
}
这样,即使您必须处理Dictionary
固有的可选性质,您的数据也更易于管理(除非您真的能够确定要从界面返回的所有键,否则很难避免这似乎是一项艰巨的任务)。
设计用作数据持有者的struct
需要您考虑数据,并且由于在这种情况下,rates
字典的keys
可能会被视为"数据",因此应相应地对其进行建模。可能不是描述您的 JSON 数据的唯一方法,而是我能立即看到的最简单的方法。
顺便说一句:下次你发布一个长字符串并有意义地将其分成几行时,请帮我们一个忙,否则很难阅读(无论如何,String
常量都很棒:-)。