bson.ObjectId 序列化与 gson

LET*_*ETs 1 java gson bson

我有一个类型为 的班级成员bson.ObjectId

序列化时,gson默认使用toString()方法,返回的值不是我想要的。我想ObjectId使用toHexString()方法进行序列化,以便获得ObjectIdHexString 格式。

如何让 gson 以ObjectIdHexString 格式序列化?

谢谢你。

LET*_*ETs 5

我解决了这个问题。我目前有一个这样的类来获取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();
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。

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

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