0

I am using gson library to handle json to body conversion. below code returns null value for toJson() method. can some one please suggest me if i miss anything.

Fruits fruits = new Fruits() {
{
setName("mango");
setPrice(10);
}
};
String body = gson.toJson(fruits); 
  • 1
    Gson does not support anonymous classes de/serialization because it cannot determine their owner types at least for the former (hence symmetry for both). Using the double brace initializer, `{{ ... }}`, **is** a pure anti-pattern. Remove the initializer block and intialize the `fruits` object in a regular way: `fruits.setName(...)` and `fruits.setPrice(...)` -- it will "magically" work (or create a _good_ `Fruits` (_Fruit_ maybe?) constructor). No idea who recommends using {{...}}, but here you go: https://stackoverflow.com/questions/924285/efficiency-of-java-double-brace-initialization – terrorrussia-keeps-killing Feb 01 '22 at 21:24
  • Then this: https://stackoverflow.com/questions/1958636/what-is-double-brace-initialization-in-java , and especially this: https://stackoverflow.com/questions/57870441/how-to-convert-nameless-objects-to-json-in-java-using-gson – terrorrussia-keeps-killing Feb 01 '22 at 21:26
  • Does this answer your question? [How to convert nameless objects to JSON in java (using GSON)?](https://stackoverflow.com/questions/57870441/how-to-convert-nameless-objects-to-json-in-java-using-gson) – terrorrussia-keeps-killing Feb 01 '22 at 21:27

0 Answers0