I have a JSON decoder but have a couple of questions. Firstly, what is the difference between what I am doing and using the JSONSerialization function?
My next question is about files and JSON. How do I go about getting a user defined file to pipe into my program to have its JSON data decoded. I am assuming that my file is in the bundle hence the second line of code, but from here I am not sure where to go.
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)