简体   繁体   English

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

[英]Applying default serializer to properties in Custom Serializer (GSON)

I am writing a custom serializer for my domain objects in GSON, so it only serializes certain objects:我正在为 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;
    }

The thing is I also want to serialize HashMaps, but this way I get values like these:问题是我也想序列化 HashMap,但这样我得到的值如下:

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

While I want the default serializing behavior Gson applies to HashMaps.虽然我希望默认序列化行为 Gson 适用于 HashMap。 How can I tell GSON to act "normally" with serializing certain objects?我怎样才能告诉 GSON 通过序列化某些对象“正常”行动?

WARNING: Answer out of date.警告:答案已过期。
Although this answer was initially accepted and upvoted, later on it's also had downvotes and comments saying it's wrong, so I guess it's out of date.虽然这个答案最初被接受和赞成,但后来也有人反对和评论说这是错误的,所以我想它已经过时了。


I'm pretty sure you can use the JsonSerializationContext context object that you have as a parameter of the serialize method.我很确定您可以使用JsonSerializationContext context对象作为serialize方法的参数。

Actually, according to Gson API documentation , this object has a method serialize that:实际上,根据Gson API 文档,这个对象有一个序列化方法:

Invokes default serialization on the specified object.对指定的对象调用默认序列化。

So I guess you just need to do something like this in the point where you want to serialize your HashMap normally :所以我想你只需要在你想要正常序列化你的HashMap地方做这样的事情:

context.serialize(yourMap);

What you COULD do is to instantiate another GsonBuilder and use that.您可以做的是实例化另一个 GsonBuilder 并使用它。 You can even append additional info, like I do in the last line of code (33% chance of being able to edit the list)你甚至可以 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

You can then include that serializedObject into your properties, or return it.然后,您可以将该 serializedObject 包含到您的属性中,或返回它。

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

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