Devnock
Devnock

Reputation: 263

Directly POST JSONObject via retrofit

Can I send JSON directly via retrofit like this:

@POST("rest/workouts")
Call<CreateWorkoutSuccessAnswer> createWorkout(@NonNull @Body JSONObject jsonObject);

Upvotes: 0

Views: 55

Answers (2)

RScottCarson
RScottCarson

Reputation: 980

You can directly post JSON objects using GSONs JsonObject class.

The reason Googles JSONObject does not work is that retrofit uses GSON by default and tries to serialize the JSONObject parameter as a POJO. So you get something like:

{
    "JSONObject":
    {
        <your JSON object here>
    }
}

If what you are doing requires you to use JSONObject then you can simply convert between the two using the String format of the object.

Upvotes: 1

Bogdan Ustyak
Bogdan Ustyak

Reputation: 5839

You can use TypedInput

@POST("rest/workouts")
Call<CreateWorkoutSuccessAnswer> createWorkout(@NonNull @Body TypedInput body);

And to form param:

TypedInput in = new TypedByteArray("application/json", jsonObject.toString().getBytes("UTF-8"));

And use in as a parameter for request.

Upvotes: 2

Related Questions