GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

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 RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's all new Paywall Editor allow you to remotely configure your paywall view without any code changes or app updates.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.