从文件和解码的 Swift JSON 数据输入

PKc*_*ion 1 json user-input swift

我有一个 JSON 解码器,但有几个问题。首先,我在做什么和使用 JSONSerialization 函数有什么区别?

我的下一个问题是关于文件和 JSON。我如何让用户定义的文件通过管道传输到我的程序中以解码其 JSON 数据。我假设我的文件在包中,因此是第二行代码,但从这里我不确定要去哪里。

let input = readLine()
let url = Bundle.main.url(forResource: input, withExtension: "json")!


struct jsonStruct: Decodable {
    let value1: String
    let value2: String
}


// JSON Example
let jsonString = """
{
"value1": "contents in value 1",
"value2": "contents in value 2"
}
"""

// Decoder
let jsonData = url.data(using: .utf8)!//doesn't work, but works if 'url' is changed to 'jsonString'
let decoder = JSONDecoder()
let data = try! decoder.decode(jsonStruct.self, from: jsonData)
print(data.value1)
print(data.value2)
Run Code Online (Sandbox Code Playgroud)

vad*_*ian 7

Codable是基于JSONSerialization并提供了一种方便的方法来直接从/到结构/类中对 JSON 进行编码/解码。

AnURL只是一个指向位置的指针。您必须Data从给定的文件中加载URL

并请以大写字母开头命名结构

struct JsonStruct: Decodable {
    let value1: String
    let value2: String
}

let url = Bundle.main.url(forResource: input, withExtension: "json")!
do {
    let jsonData = try Data(contentsOf: url)
    let decoder = JSONDecoder()
    // the name data is misleading
    let myStruct = try decoder.decode(JsonStruct.self, from: jsonData)
    print(myStruct.value1)
    print(myStruct.value2)

} catch { print(error) }
Run Code Online (Sandbox Code Playgroud)