繁体   English   中英

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

[英]Applying default serializer to properties in Custom Serializer (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 context对象作为serialize方法的参数。

实际上,根据Gson API 文档,这个对象有一个序列化方法:

对指定的对象调用默认序列化。

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

context.serialize(yourMap);

您可以做的是实例化另一个 GsonBuilder 并使用它。 你甚至可以 append 附加信息,就像我在最后一行代码中所做的那样(33% 的机会能够编辑列表)

final GsonBuilder gb = new GsonBuilder();
JsonObject serializedObject = (JsonObject) gb.create().getAdapter(HashMap.class).toJsonTree(yourMap);
serializedObject.addProperty("canEdit", Math.random < 0.33); // append additional info

然后,您可以将该 serializedObject 包含到您的属性中,或返回它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM