使用gson进行bson.ObjectId序列化

时间:2016-02-18 16:27:27

标签: java gson bson

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

序列化后,gson默认使用toString()方法,返回的值不是我想要的。我想使用ObjectId方法序列化toHexString(),以便我可以使用HexString格式获取ObjectId

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

谢谢。

1 个答案:

答案 0 :(得分:4)

我解决了这个问题。 我目前有一个这样的类来获取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

顺便说一下,参考代码没有用,并且有一些小错误。 我解决了我的问题。