我正在为我的领域对象编写自定义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以正常方式序列化某些对象?