将默认序列化程序应用于Custom Serializer(GSON)中的属性

时间:2013-09-18 07:11:27

标签: 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;
    }

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

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

虽然我希望默认的序列化行为Gson适用于HashMaps。如何通过序列化某些对象来告诉GSON“正常”行事?

1 个答案:

答案 0 :(得分:2)

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

实际上,根据Gson API documentation,此对象有一个序列化方法:

  

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

所以我想你只需要做一些像这样的事情,你想要正常地序列化HashMap

context.serialize(yourMap);
相关问题