WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

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      

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.