toecsnar42
toecsnar42

Reputation: 473

Parse JSON to struct with one function

I can't find any answer on how to parse json from response Data object automatically if we know the response type. I'm quite new to swift, therefore my solution may be not ideal, but I believe it does what it was supposed to do - parse Data to swift struct with just one short line of code.

First, I extended Decodable protocol

extension Decodable {
    static func parse(from data: Data) -> Self?{
        let decoder = JSONDecoder()
        let json = try? decoder.decode(Self.self, from: data)
        return json
    }
}

then if I define example struct

struct Example: Decodable {
    let a: String
    let b: Int
}

and have some data

let data = """
{"a": "Test", "b": 5}
""".data(using: .utf8)
print(Example.parse(from: data!))

I wanted to have automatically parsed response while could not find such answer on the Internet. Of course, we need to take care of nil and Example object is Optional, but this can be handled by external function. Is there any reason why this code is not safe, or for whatever reason not recommended to use?

Upvotes: 0

Views: 75

Answers (1)

Rob Napier
Rob Napier

Reputation: 299345

Typically this isn't done because it assumes that the only format the data can be encoded in is JSON (Codable supports other formats), and that you never intend to configure the decoder (Decoders have several configuration options).

Your code also throws away JSON parsing errors, which is not ideal, though may be convenient for some uses.

If your project never has any of those issues, and you want a shorter syntax for your special case, then it's fine to add any extension you like. That's what extensions are for.

I would suggest you rethink the try? however. Throwing away errors and turning them into nil makes debugging much harder. But again, it's up to you. Build any extension that is convenient for you.

Upvotes: 2

Related Questions