java - 将默认序列化程序应用于自定义序列化程序 (GSON) 中的属性

标签 java json gson

我正在为 GSON 中的域对象编写自定义序列化程序,因此它只序列化某些对象:

 @Override
    public JsonElement serialize(BaseModel src, Type typeOfSrc, JsonSerializationContext context) {

        JsonObject obj = new JsonObject();


        Class objClass= src.getClass();

        try {
            for(PropertyDescriptor propertyDescriptor : 
                Introspector.getBeanInfo(objClass, Object.class).getPropertyDescriptors()){

                                    if(BaseModel.class.isAssignableFrom(propertyDescriptor.getPropertyType()))
                {
                    //src.getId()
                }
                else if(Collection.class.isAssignableFrom(propertyDescriptor.getPropertyType()))
                {
                    //whatever
                }
                else {
                    String value = (propertyDescriptor.getReadMethod().invoke(src)) != null?propertyDescriptor.getReadMethod().invoke(src).toString():"";
                    obj.addProperty(propertyDescriptor.getName(), value);
                }
            }
        } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        return obj;
    }

问题是我也想序列化 HashMap,但这样我得到的值如下:

{"key"=com.myproject.MyClass@28df0c98}

虽然我希望 Gson 的默认序列化行为适用于 HashMap。我怎样才能告诉 GSON 以“正常”方式序列化某些对象?

最佳答案

警告:答案已过时。
虽然这个答案最初被接受和投票,但后来也有反对票和评论说它是错误的,所以我想它已经过时了。


我很确定您可以使用 JsonSerializationContext 上下文 对象作为 serialize 方法的参数。

其实根据Gson API documentation ,这个对象有一个序列化方法:

Invokes default serialization on the specified object.

所以我猜你只需要在你想要序列化你的HashMap 正常的时候做这样的事情:

context.serialize(yourMap);

关于java - 将默认序列化程序应用于自定义序列化程序 (GSON) 中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18865955/

相关文章:

java - 继承和隐藏方法和类的问题

android - 如何在 WIndows 7 64 位上将 JDK 而不是 JRE 设置为默认 JVM?

javascript - Highcharts 显示空白

java - 如何在 java 中使用 com.google.gson.JsonObject 将值设置为 null?

java - Gson:要列出的索引对象

java - Spring Boot mongo审核@version问题

Java:线程不起作用

php - 如何使用 AngularJS 显示存储在 MySQL 中的 json 对象

r - 使用 data.table 写入和加载 JSON 字符串

java - 序列化 VS Gson