Reputation: 5770
I am writing a custom serializer for my domain objects in GSON, so it only serializes certain objects:
@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:
{"key"=com.myproject.MyClass@28df0c98}
While I want the default serializing behavior Gson applies to HashMaps. How can I tell GSON to act "normally" with serializing certain objects?
Upvotes: 3
Views: 2050
Reputation: 2576
What you COULD do is to instantiate another GsonBuilder and use that. You can even append additional info, like I do in the last line of code (33% chance of being able to edit the list)
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.
Upvotes: 0
Reputation: 18741
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.
Actually, according to Gson API documentation, this object has a method serialize that:
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:
context.serialize(yourMap);
Upvotes: 3