2

I've been trying out Retrofit and I really it's simplicity.

However I have an otimization concern. I'm using Parse for my backend and it has a pure Rest API.

When I want to update an object I use a PUT HTTP Request and pass in the body only the specific values I want to update.

However, using Retrofit I always have to serialize the entire object when passing it using the @Body annotation. If I have a very large object, this is very inneficient.

All the solutions I see is using Annotations to inform the Converter which fields are exposed. However this affects all requests and won't work if I have different update methods for updating different fields.

I think I have two options:

  1. Pass the parameters I want to update as Form parameters and use the @URLEncoded annotation. However this is not really RESTful and I don't think Parse supports it.
  2. Create an annotation to inform which fields should be added to JSON in the body. For doing this, how can I access the method's annotations in the Converter, in order to select which fields to serialize?
ffleandro
  • 4,039
  • 4
  • 33
  • 48
  • You could have a look at this question: http://stackoverflow.com/questions/18491733/gson-serialize-field-only-if-not-null-or-not-empty and the respective answers. Would that help? – david.mihola Jun 05 '15 at 18:45
  • Sort of. But inside the Converter, how would I now which fields does the user want to serialize? I could create an annotation in the specific service method, but inside the GsonConverter how can I access this annoation? – ffleandro Jun 05 '15 at 19:50

1 Answers1

2

Retrofit uses Gson by default. And Gson excludes null values by default. So it shouldn't be a problem (unless you are using primitive types in your object)

andrei
  • 2,934
  • 2
  • 23
  • 36
  • That is not what I'm trying to do. I want to be able to choose which fields from an object to send in the body request. All solutions I've seen are through annotations, however that impacts all requests with the same object. – ffleandro Aug 17 '15 at 15:28
  • If you create a new object and set just the fields that you are interested in, all the other fields will be null, not serialized by Gson and will not be sent in the body – andrei Aug 17 '15 at 15:30
  • @ffleandro I tried with both PUT and PATCH (which I use for update) and after looking at the request in charles proxy I can confirm that only the initialized fields are being sent – andrei Aug 17 '15 at 15:53
  • I understand that, but I want to filter specific fields, not only the initialized. For instance I want to send fields `a` and `c` on a request, and only `a` and `b` on another request of the same endpoint. – ffleandro Aug 17 '15 at 18:12
  • How about primitive fields? How can you exclude them from the body? – Stan May 16 '18 at 14:18
  • @Stan you can register TypeAdapters with Gson. Have a look here https://futurestud.io/tutorials/retrofit-2-adding-customizing-the-gson-converter – andrei May 16 '18 at 14:27