I have a class member with type bson.ObjectId
.
When serialized, gson
by default uses toString()
method and the returned value is not what I want. I would like to serialize ObjectId
using toHexString()
method instead so I could get ObjectId
in HexString format.
How do I make gson to serialize ObjectId
in HexString format?
Thank you.
I solved the problem.
I currently have a class like this to get Gson
object and it works well for me.
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import org.bson.types.ObjectId;
import java.lang.reflect.Type;
public class GsonUtils {
private static final GsonBuilder gsonBuilder = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.registerTypeAdapter(ObjectId.class, new JsonSerializer<ObjectId>() {
@Override
public JsonElement serialize(ObjectId src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.toHexString());
}
})
.registerTypeAdapter(ObjectId.class, new JsonDeserializer<ObjectId>() {
@Override
public ObjectId deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return new ObjectId(json.getAsString());
}
});
public static Gson getGson() {
return gsonBuilder.create();
}
}
Hope this helps.
Reference: http://max.disposia.org/notes/java-mongodb-id-embedded-document.html
Btw, Reference's code doesn't work and has some minor errros. I fixed those problems in mine.