bson.ObjectId 使用 gson 序列化

bson.ObjectId serialization with gson

我有一个 class 类型为 bson.ObjectId 的成员。

序列化时,gson默认使用toString()方法,返回值不是我想要的。我想使用 toHexString() 方法序列化 ObjectId,这样我就可以得到 HexString 格式的 ObjectId

如何让 gson 以 HexString 格式序列化 ObjectId

谢谢。

我解决了这个问题。 我目前有一个像这样的 class 来获取 Gson 对象,它对我来说效果很好。

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();
    }
}

希望对您有所帮助。

参考:http://max.disposia.org/notes/java-mongodb-id-embedded-document.html

顺便说一句,参考的代码不起作用并且有一些小错误。 我解决了我的这些问题。