Android - Annotating Retrofit2 POST / PATCH Request Body with something similar to @SerializedName The Next CEO of Stack OverflowJSONObject.toString: how NOT to escape slashessingle key value to Json with GsonJava Append object to JSONGSON: how to prevent StackOverflowError while keeping circular references?Create JSON using GSON with a colon as part of a field's nameChange default enum serialization & deserialization in gsonParse nested json data into stringClassCastException Object Inheritance with RetrofitRetrofit 2+ with Gson is showing error when attempt to populate recyclerviewFirebase Java SDK serialized POJO not using gson annotationIs there a way of GSON to be “not lenient” at all?Questions on Gson and Java model classRetrofit2 POST body as raw JSON

What did the word "leisure" mean in late 18th Century usage?

How do I secure a TV wall mount?

Is it correct to say moon starry nights?

Is it OK to decorate a log book cover?

Incomplete cube

Ising model simulation

"Eavesdropping" vs "Listen in on"

Simplify trigonometric expression using trigonometric identities

That's an odd coin - I wonder why

How can a day be of 24 hours?

Are British MPs missing the point, with these 'Indicative Votes'?

Why was Sir Cadogan fired?

Why doesn't Shulchan Aruch include the laws of destroying fruit trees?

Calculate the Mean mean of two numbers

MT "will strike" & LXX "will watch carefully" (Gen 3:15)?

Is it possible to make a 9x9 table fit within the default margins?

How dangerous is XSS

How should I connect my cat5 cable to connectors having an orange-green line?

Is a distribution that is normal, but highly skewed, considered Gaussian?

Why do we say “un seul M” and not “une seule M” even though M is a “consonne”?

Mathematica command that allows it to read my intentions

Compensation for working overtime on Saturdays

Why did the Drakh emissary look so blurred in S04:E11 "Lines of Communication"?

Is it possible to create a QR code using text?



Android - Annotating Retrofit2 POST / PATCH Request Body with something similar to @SerializedName



The Next CEO of Stack OverflowJSONObject.toString: how NOT to escape slashessingle key value to Json with GsonJava Append object to JSONGSON: how to prevent StackOverflowError while keeping circular references?Create JSON using GSON with a colon as part of a field's nameChange default enum serialization & deserialization in gsonParse nested json data into stringClassCastException Object Inheritance with RetrofitRetrofit 2+ with Gson is showing error when attempt to populate recyclerviewFirebase Java SDK serialized POJO not using gson annotationIs there a way of GSON to be “not lenient” at all?Questions on Gson and Java model classRetrofit2 POST body as raw JSON










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?



Is there an easy way to do it (some GSON annotation maybe) or is my only option to make 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.)










share|improve this question




























    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?



    Is there an easy way to do it (some GSON annotation maybe) or is my only option to make 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.)










    share|improve this question


























      2












      2








      2


      1






      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?



      Is there an easy way to do it (some GSON annotation maybe) or is my only option to make 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.)










      share|improve this question
















      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?



      Is there an easy way to do it (some GSON annotation maybe) or is my only option to make 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.)







      java post request gson retrofit2






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 7 at 20:33







      Madelyn Luansing

















      asked Mar 7 at 19:43









      Madelyn LuansingMadelyn Luansing

      134




      134






















          1 Answer
          1






          active

          oldest

          votes


















          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:



          • single key value to Json with Gson

          • JSONObject.toString: how NOT to escape slashes

          • Java Append object to JSON





          share|improve this answer


















          • 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 7 at 20:50











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55051686%2fandroid-annotating-retrofit2-post-patch-request-body-with-something-similar%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          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:



          • single key value to Json with Gson

          • JSONObject.toString: how NOT to escape slashes

          • Java Append object to JSON





          share|improve this answer


















          • 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 7 at 20:50















          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:



          • single key value to Json with Gson

          • JSONObject.toString: how NOT to escape slashes

          • Java Append object to JSON





          share|improve this answer


















          • 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 7 at 20:50













          0












          0








          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:



          • single key value to Json with Gson

          • JSONObject.toString: how NOT to escape slashes

          • Java Append object to JSON





          share|improve this answer













          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:



          • single key value to Json with Gson

          • JSONObject.toString: how NOT to escape slashes

          • Java Append object to JSON






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 7 at 20:32









          Madelyn LuansingMadelyn Luansing

          134




          134







          • 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 7 at 20:50












          • 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 7 at 20:50







          1




          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 7 at 20:50





          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 7 at 20:50



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55051686%2fandroid-annotating-retrofit2-post-patch-request-body-with-something-similar%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

          Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

          Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved