使用GSon将匿名Java对象类型转换为JSON [英] Convert Anonymous java object types to JSON using GSon

查看:442
本文介绍了使用GSon将匿名Java对象类型转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 对象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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆