Moya: Implicit JSON serialization for BODY parameters of POST request like Retrofit in Android

Created on 11 Jul 2017  ·  5Comments  ·  Source: Moya/Moya

Hi everyone,
First of all, thanks for such an awesome library. The problem I am having is to send custom objects as parameters for POST BODY request. For example my endpoint expects the following json format

{
user: {
"email": "[email protected]",
"address": "xyz"
},
"parameter": "value"
}

In general, it can be a complicated json object that can map to a Swift model X for example.

In Retrofit (the android counterpart), this works out of the box like

Call xRequest(@Body X request);

Do we have a tool for implicit json serialization from X to json in Moya?

question

All 5 comments

Hey @sandeepbol. This is a good question!

Unfortunately, we do not have such solution built-in Moya core. This might change when we migrate to Swift 4, in fact there are already plans on implementing such functionality (#1135, #1147). For now you would have to do the object mapping to JSON manually. However, there are libraries out there that can help with that, like Wrap by John Sundell - you could give it a try.

Please let me know if you have any further questions regarding this topic!

Thanks a lot @sunshinejr for help. That did the trick. Actually an unrelated question:

How is

return endpoint.adding(newParameterEncoding: JSONEncoding.default)

different from

defining parameterEncoding like this

    public var parameterEncoding: ParameterEncoding {
        switch self {
        case .login, .enrollUser, .resetPassword, .choosePassword:
            return JSONEncoding.default
        default:
            return URLEncoding.default
        }
    }

The latter worked for me with Wrap library.

Setting parameterEncoding in endpointClosure (first option) was an option long before parameterEncoding in TargetType (second option). The first one is more generic - you can have one closure that handles multiple providers/target types (so you can setup one encoding for an entire API or for some part of the endpoints), where the second one is more TargetType specific (sometimes you just want different encoding for one endpoint, not for a whole API, thus this option).

Also when you use both methods at the same time, the endpointClosure one will override the TargetType one, since it is executed after.

But both of them are setting the ParameterEncoding, which is the same functionality, but for kinda different use-cases.

Also, because I think your issue is resolved for now, I'm gonna close this issue. If you find yourself getting more questions about Moya, don't hesitate to open a new one!

Saved my day! Thx

Was this page helpful?
0 / 5 - 0 ratings

Related issues

syq7970 picture syq7970  ·  3Comments

kamwysoc picture kamwysoc  ·  3Comments

hjzCy picture hjzCy  ·  3Comments

sunshinejr picture sunshinejr  ·  3Comments

mwawrusch picture mwawrusch  ·  3Comments