1

Is there any simple way in Retrofit to convert passed object to JSON automatically?

This is my Retrofit interface :

@FormUrlEncoded
@POST("/places/name")
void getPlacesByName(@Field("name") String name,
                     @Field("city") String city,
                     @Field("tags") Tags tags,
                     Callback<PlaceResponse> callback);

At first I thought that if I pass Tags object it will be automatically converted to JSON , but in reality request looks like this : name=pubs&city=London&tags=com.app.database.model.Tags%4052aa38a8

Is there any simple way to convert POJO to JSON in Retrofit?

Vishwajit Palankar
  • 3,033
  • 3
  • 28
  • 48
filipp.kowalski
  • 5,495
  • 7
  • 27
  • 45
  • 1
    Take a look at this answer http://stackoverflow.com/questions/21398598/how-to-post-raw-whole-json-in-the-body-of-a-retrofit-request. You need to define a @Body parameter and feed it a POJO. – Edson Menegatti Jun 01 '15 at 16:03
  • I've tried that but if I use `@Body` I will get this error `@Body parameters cannot be used with form or multi-part encoding` – filipp.kowalski Jun 01 '15 at 16:07
  • If you use @Body you should remove the FormUrlEncoded annotation Retrofit will do the rest. – Ivan Wooll Jun 01 '15 at 16:23
  • or override the `toString` method of your object to return a json representation – njzk2 Jul 03 '15 at 22:35

2 Answers2

2

You are creating a URL with parameters because you're using the @URLEncoded and passing the parameters as @Field.

Here is the solution:

@POST("/places/name")
void getPlacesByName(@Body RequestObject req, Callback<PlaceResponse> callback);

Additionaly, I would advise on using @GET for retrieving objects. @POST is used for creating an object and @PUT for updating. Although this isn't wrong, it as recomendation in order be RESTful compliant.

ffleandro
  • 4,039
  • 4
  • 33
  • 48
1

Use Jackson to convert it directly to a String:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);

Or use Gson: http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

Sandro Machado
  • 9,921
  • 4
  • 36
  • 57