AHméd Net AHméd Net - 8 months ago 85
Java Question

Convert Anonymous java object types to JSON using GSon

is there any possibility to serialize anonymous object type to JSON using Gson or any else library on JAVA ?

Object objResult = new Object() {
boolean success = true;
String email="mail@gmail.com";

String jsonstr = gson.toJson(objResult);

jsonstr : null !!


Gson doesn't support that feature. From the user guide

Fields corresponding to the outer classes in inner classes, anonymous classes, and local classes are ignored and not included in serialization or deserialization

You can use a Class (or other Type) representing the superclass of the anonymous type to describe what to serialize using the overloaded toJson(Object, Type) method, but you'll still lose any new fields defined in the anonymous subclass. (Obviously, with Object, this does nothing, since Object has no fields.)