I need to send HTTP PUT request with custom JSON object in one of request's parameter. Here is a problem: when I use it with Retrofit2, my serializer doesn't called.
My object should looks like this:
{
"ignore":["item1", "item2"]
}
When I call it directly it works well:
final Gson gson = new GsonBuilder()
.registerTypeAdapter(MyModel.class, new MyModelSerializer())
.create();
String s = gson.toJson(new MyModel(MyModel.ActionName.ACCEPT, new ArrayList<String>()));
Log.d("tag", s);
I get {"accept":[]}
. But when I call it with Retrofit I see in logs this: D/OkHttp: name=abc&items=ru.bartwell.myapp.MyModel%4010a3d8b
I make request with this code:
try {
MyModel myModel = new MyModel(MyModel.ActionName.ACCEPT, new ArrayList<String>());
Response<ResultModel> response = getMyApi().getResult(1, "abc", myModel).execute();
if (response.isSuccessful()) {
ResultModel resultModel = response.body();
// handle resultModel
}
} catch (Exception e) {
e.printStackTrace();
}
MyApi:
@FormUrlEncoded
@PUT("path/{id}")
Call<ResultModel> getResult(@Path("id") long item, @Field("name") @NonNull String name, @Field("items") @NonNull MyModel myModel);
getMyApi() method:
public static MyApi getMyApi() {
final Gson gson = new GsonBuilder()
.registerTypeAdapter(MyModel.class, new MyModelSerializer())
.create();
return new Retrofit.Builder()
.baseUrl(BuildConfig.END_POINT_MY_API)
.client(MyOkHttpClient.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
.create(MyApi.class);
}
Model:
public class MyModel {
@NonNull
private ActionName mActionName;
@NonNull
private List<String> mItems = new ArrayList<>();
public MyModel(@NonNull final ActionName actionName, @NonNull final List<String> items) {
mActionName = actionName;
mItems = items;
}
@NonNull
public ActionName getActionName() {
return mActionName;
}
@NonNull
public List<String> getItems() {
return mItems;
}
public enum ActionName {
ACCEPT("accept"), DECLINE("decline"), IGNORE("ignore");
private String mName;
ActionName(@NonNull final String name) {
mName = name;
}
public String getName() {
return mName;
}
}
}
Serializer:
public class MyModelSerializer implements JsonSerializer<MyModel> {
@Override
public JsonElement serialize(@NonNull MyModel src, @NonNull Type typeOfSrc, @NonNull JsonSerializationContext context) {
JsonObject obj = new JsonObject();
obj.add(src.getActionName().getName(), new Gson().toJsonTree(src.getItems()));
return obj;
}
}
How to fix it?