SwiftUI 读取 json 文件

2019-10-29  本文已影响0人  小凡凡520
struct PageView: View {
    
    @EnvironmentObject var model:MainViewModel
    
    var body: some View {
        Text("\(model.name)")
    }
}

struct PageView_Preview: PreviewProvider {
    
    static var previews: some View {
        PageView()
    }
}




class MainViewModel: ObservableObject {
    
    var name:String = ""
    
    init() {
        let name = InitializationHelper.loadJson(fileName: "1")?.first?.name ?? "chen"
        
        self.name = name
    }
}

class InitializationHelper {
    
    struct ResponseData:Decodable {
        var currencies: [InititalCurrency]
    }
    
    static func loadJson(fileName: String) -> [InititalCurrency]? {
        if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
            do {
                let data = try Data(contentsOf: url)
                let jsonData = try JSONDecoder().decode(ResponseData.self, from: data)
                return jsonData.currencies
            } catch {
                print(error.localizedDescription)
            }
            
        }
        return nil
    }
}

class InititalCurrency: Identifiable, Codable {
    
    var name: String
    var longName: String
    var symbol: String

    private enum CodingKeys: String, CodingKey {
        case name
        case longName
        case symbol
    }
    
    init(
        name: String,
        longName: String,
        symbol: String
    ) {
        self.name = name
        self.longName = longName
        self.symbol = symbol
    }
    
    required public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
        longName = try container.decode(String.self, forKey: .longName)
        symbol = try container.decode(String.self, forKey: .symbol)
    }
}






// json文件内容
{
  "currencies": [
    {
      "name": "AED",
      "longName": "United Arab Emirates dirham",
      "symbol": "\u062f.\u0625"
    },
    {
      "name": "AFN",
      "longName": "Afghan afghani",
      "symbol": "\u060b"
    }
  ]
}


上一篇下一篇

猜你喜欢

热点阅读