Convert Anonymous java object types to JSON using GSon

后端 未结 2 827
予麋鹿
予麋鹿 2020-12-03 18:54

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

Object objResult = new Object() {
                     


        
相关标签:
2条回答
  • 2020-12-03 19:38

    If you use MyClass(){{}} inline syntax use Gson.toJson(obj, type) overloaded method.

    MyClass obj = new MyClass(){{}};
    new Gson.toJson(obj, obj.getClass().getSuperclass())
    

    Anonymous class names contains $ letter. So to get exact class use

    Type type = obj.getClass();
    while(type.toString.Contains("$")) type = ((Class)type).getSuperclass();
    new Gson.toJson(obj, type);
    
    0 讨论(0)
  • 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.)

    0 讨论(0)
提交回复
热议问题