我有一个 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)