Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将默认序列化程序应用于自定义序列化程序(GSON)中的属性_Java_Json_Gson - Fatal编程技术网

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

Java 将默认序列化程序应用于自定义序列化程序(GSON)中的属性,java,json,gson,Java,Json,Gson,我正在为GSON中的域对象编写自定义序列化程序,因此它只序列化某些对象: @Override public JsonElement serialize(BaseModel src, Type typeOfSrc, JsonSerializationContext context) { JsonObject obj = new JsonObject(); Class objClass= src.getClass(); try {

我正在为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,但通过这种方式,我得到如下值:

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


虽然我希望Gson的默认序列化行为适用于HashMaps。如何让GSON在序列化某些对象时“正常”操作?

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


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

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

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

因此,我想您只需要在希望序列化
HashMap
的时候执行类似的操作:


对我来说,它将使用自定义序列化,这将在一个无限循环中结束…函数的文档字面上说不要这样做:“在传递特定类型信息的指定对象上调用默认序列化。永远不要在作为JsonSerializer.serialize参数接收的元素上调用它(对象、类型、JsonSerializationContext)方法。这样做将导致无限循环,因为Gson将再次调用自定义序列化程序。“
context.serialize(yourMap);