javaandroidretrofit

Retrofit: Sending POST request with JSON Array


I have JsonElement jsonElement object which I receive as response from my another GET request. jsonElement.toString(); looks like JSON array:

[{"Id":493,"Number":"380931112233","FriendNumber":"3806822233344"},{"Id":494,"Number":"380931112233","FriendNumber":"3806388886667"}]

I need to send this string via another POST request using Retrofit. How can I send jsonElement or String object via POST request? How should look declaration of my method? For example:

 @POST("/api/geo/getLoc")
    public void getFriendsLocation(/* something */,  Callback<JsonElement> response);

Solution

  • If you are sending data over request body your implementation should be like this:

    1. Define model according to fields (CaseSensitive "Name" -> String Name etc )
    2. set your api function also like that

      @POST("/api/geo/getLoc")
      public void getFriendsLocation(@Body YourClass classObject,   Callback<JsonElement> response);
      
    3. Use directly your created class object on post request

      getFriendsLocation(yourClassObjectThatIncludesFields, new Callback .... )
      

    If your sending data over params You can do this with Gson.

    1. Lets say you have a class that have fields like id , number and FriendNumber.Define a function :

      public static Map<String, Object> getMapFromObject(Object o) {
          Gson gson = new Gson();
          Type stringObjectMap = new TypeToken<Map<String, Object>>() {
           }.getType();
          return gson.fromJson(gson.toJson(o), stringObjectMap);
      }
      
    2. set your api function also like that

      @POST("/api/geo/getLoc")
      public void getFriendsLocation(@QueryMap Map<String, Object>,     Callback<JsonElement> response);
      
    3. When you are sending post request create object from your fields call this function like below here

      getFriendsLocation(getMapFromObject(yourClassObjectThatIncludesFields), new Callback .... )
      

    I didnt write whole code which includes class definition and Callback function because they are up to your customization. I assume that you need to send over body so try the first way.