【问题标题】:bson.ObjectId serialization with gsonbson.ObjectId 用 gson 序列化
【发布时间】:2019-06-12 10:34:35
【问题描述】:

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

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

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

谢谢。

【问题讨论】:

    标签: java gson bson


    【解决方案1】:

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

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

    【讨论】:

    • Pojo 类中用于保存 ObjectId 的字段名称和数据类型是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2015-07-11
    • 1970-01-01
    • 2012-10-26
    相关资源
    最近更新 更多