[Codable] decoding JSON and map it to existing object

I am using ObjectMapper for most of my projects inside NetworkManager and I tried to use Codable after WWDC17 I even create public library to use it but without luck is because it creates new object every time. this is not the case all the time.

for example imaging we have two requests

first request will respond with this

{
    "balance": 45.30
}

and second request will respond with this

{
    "purchased": [
        "iPhone",
        "iPad",
        "Macbook Pro"
    ]
}

and swift object

struct Wallet: Codable {

    private(set) var balance: Double
    var purchased = [String]()

    func requestBalance() { ... }
    func requestPurchased() { ... }

}

when use let wallet = try! decoder.decode(Wallet.self, for: jsonData) will create new object.

Object mapper have this class function

let wallet = Mapper<Wallet>().map(JSONObject: jsonData, toObject: object)

which will map the coming JSON data to the existing object and also create new one with just the new data. This approach been very helpful in almost every situation.

I propose to overload function decode with decode(Wallet.self, for: jsonData, to: Object) to have the same functionality

1 Like

How can you decode Wallet from the partial JSON responses at all when they miss the required fields? For example, how do you decode Wallet from {"balance": 45.30} when it misses the required purchased field? (And if you mark all fields as optional, don’t you lose a lot of safety?)

As for “merging” the response with an existing object, I would be interested in a working approach, too. (Although that’s better discussed in #swift-users, not #evolution, I think.) My first naïve idea would be to decode the incoming JSON response into a dictionary, encode the existing object into a dictionary, merge the dictionaries (resolving conflicts) and then decode the merged object from that. Sounds horrible.

I am interested too. Has there been any good solutions on this?

Try this approach.