This question may have been asked before but no it was not definitively answered. How exactly does one post raw whole JSON inside the body of a Retrofit request?
See similar question here. Or is this answer correct that it must be form url encoded and passed as a field? I really hope not, as the services I am connecting to are just expecting raw JSON in the body of the post. They are not set up to look for a particular field for the JSON data.
I just want to clarify this with the restperts once and for all. One person answered not to use Retrofit. The other was not certain of the syntax. Another thinks yes it can be done but only if its form url-encoded and placed in a field (that's not acceptable in my case). No, I can't re-code all the services for my Android client. And yes, it's very common in major projects to post raw JSON instead of passing over JSON content as field property values. Let's get it right and move on. Can someone point to the documentation or example that shows how this is done? Or provide a valid reason why it can/should not be done.
UPDATE: One thing I can say with 100% certainty. You CAN do this in Google's Volley. It's built right in. Can we do this in Retrofit?
1)Add dependencies-
2) make Api Handler class
3)make bean classes from Json schema 2 pojo
http://www.jsonschema2pojo.org/
4)make interface fro api calling
5)make JsonObject for passing in to body as parameter
6) Call Api Like this
The
@Body
annotation defines a single request body.Since Retrofit uses Gson by default, the
FooRequest
instances will be serialized as JSON as the sole body of the request.Calling with:
Will yield the following body:
The Gson docs have much more on how object serialization works.
Now, if you really really want to send "raw" JSON as the body yourself (but please use Gson for this!) you still can using
TypedInput
:TypedInput is a defined as "Binary data with an associated mime type.". There's two ways to easily send raw data with the above declaration:
Use TypedByteArray to send raw bytes and the JSON mime type:
Subclass TypedString to create a
TypedJsonString
class:And then use an instance of that class similar to #1.
Based on the top answer, I have a solution to not have to make POJOs for every request.
Example, I want to post this JSON.
then, I create a common class like this:
Finally, when I need a json
The request marked annotation
@Body
then can pass to Retrofit.In Retrofit2, When you want to send your parameters in raw you must use Scalars.
first add this in your gradle:
Your Interface
Activity
I tried this: When you are creating your Retrofit instance, add this converter factory to the retrofit builder: