我正在为 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/