2

If the POST / PATCH body needs to look like this

{
    "class_name" : {
        "field_a" : "fjdksljf"
        "field_b" : "jfsljd"
        ...
        etc.
    }
}

and I have a POJO

public class ClassName () {

    @SerializedName("field_a")
    String fieldA;

    @SerializedName("field_b")
    String fieldB;

    ... etc.
}

and I want to pass it as

@PATCH("endpoint_url")
Call<ResponseBody> testFunction(@Body ClassName class)

How can I annotate the class itself with the class_name mapping needed for the JSON request without creating a RequestClass that wraps ClassName and annotates it with serialized name there?

(I tried annotating the class with @SerializedName but it gives me a "not applicable to type" warning.)

Sampson
  • 662
  • 6
  • 17

1 Answers1

0

This ended up being a good solution for me. While it is possible to wrap it in another class, it doesn't really make sense in my use case since most of my POST bodies require a JSON key for the POJO I'm sending.

// to use the necessary @SerializedName annotations
String classNameJson = new Gson().toJson(className);    // {"field_a": "fjdksljf", "field_b" : "jfsljd", ... etc.}
JSONObject json = new JSONObject();
try {
     // must make this a new JSONObject or else it will handle classNameJson as a string and append unnecessary quotes
     json.put("class_name", new JSONObject(classNameJson));    
} catch (JSONException e) {
     // handle the error
}
String result = json.toString();

Result should print something like this {"class_name":{"field_a": "fjdksljf", "field_b" : "jfsljd", ... etc.}}

Got this idea from the following posts:

Sampson
  • 662
  • 6
  • 17
  • 1
    Even so this code works properly using `POJO` structure is much better idea because maintenance is easier. After a while it will be hard to understand what this code does. See @Deadpool answer. It is much better in my opinion. – Michał Ziober Mar 07 '19 at 20:50