使用GSon将匿名Java对象类型转换为JSON [英] Convert Anonymous java object types to JSON using GSon
问题描述
对象objResult =是否有可能使用Gson或JAVA上的任何其他库将匿名对象类型序列化为JSON? new Object(){
boolean success = true;
字符串电子邮件=mail@gmail.com;
};
String jsonstr = gson.toJson(objResult);
在这个例子中,字符串jsonstr返回一个空值。
Gson不支持该功能。从用户指南
与内部类中的外部类,匿名
类和本地类相对应的字段将被忽略并且不包含在
序列化或反序列化中。
您可以使用 Class
(或其他 Type
)表示匿名类型的超类,用于描述使用重载的 toJson(Object,Type)
方法,但仍然会失去匿名子类中定义的任何新字段。 (显然,使用 Object
,这没有任何作用,因为 Object
没有字段。)
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);
In this example, the string jsonstr returns a null value.
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.)
这篇关于使用GSon将匿名Java对象类型转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!