1

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)
PKconversion
  • 71
  • 1
  • 7
  • Difference between `Codable` & `(NS)JSONSerialization`? Less code because the keys are more "internally" interpreted. Usually, you need to do with `(NS)JSONSerialization` : `let value1 = jsonDict["value1"]`, which isn't needed here. `url.data(using: .utf8)!`, that's transforming the `url` (which is a "Path"/URL) into `(NS)Data` that's not reading the content at the url/path `url`. That's why it fails. It's like transforming "http://stackoverflow.com" into `(NS)Data` (the string) instead of fetching the content at that URL. – Larme Aug 27 '18 at 07:46

1 Answers1

7

Codable is based on JSONSerialization and provides a convenient way to en/decode JSON directly from/into structs/classes.

An URL is just a pointer to a location. You have to load the Data from the file at given URL

And please name the struct with a starting capital letter

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) }
vadian
  • 274,689
  • 30
  • 353
  • 361