TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Looking for an easy way to decode JSON into an object, but with partial data

Forums > Swift

One of the shortcomings of JSONDecoder is that it always creates a full object. For my use-case, this is not enough, because my API will send incremental changes, i.e. only the properties of an object that have been changed on server-side. So I am wondering how I can best handle this scenario with Swift.

In JavaScript, this would be pretty easy, using the spread operator, e.g.:

user = {
  ...user,
  ...partialUserData
}

The only solution I have found for Swift this far is rather complex:

stablekernel{.}com/article/understanding-extending-swift-4-codable/

Is there any better / easier solution with the latest Swift versions?

(I also found SwiftyJSON. This actually resembles the way a JSON library for C# I was using implemented it. However, this approach requires to setup the model objects from the parsed JSON yourself. Also, the maintainers seem to have dropped the project.)

2      

My first thought would be to do something like this:

Make an extension to the struct that represents a full JSON response but with optionals:

struct Person : Codable {
    var name: String?
    var height: Double?
    var weight: Double?
    //etc.
}
extension Person {

    mutating func merge(newData: Data) {
        let decoder = JSONDecoder()
        if let updatedPerson = try? decoder.decode(Person.self, newData) {
                self.name = updatedPerson.name ?? self.name
                self.height = updatedPerson.height ?? self.height
                //etc.
        }
    } 
}

And then somewhere else:

func callAPI() {
     //some set up that gets a response
     Person.merge(newData: response)
}

Thoughts on this? I guess this is a bit complex too, though its the only way I can think of doing it.

2      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.