JSON.NET cast error when serializing Mongo ObjectId

后端 未结 6 1246
旧巷少年郎
旧巷少年郎 2020-11-28 09:36

I am playing around with MongoDB and have an object with a mongodb ObjectId on it. When I serialise this with the .NET Json() method, all is good (but the dates are horrible

6条回答
  •  萌比男神i
    2020-11-28 09:48

    1) Write ObjectId converter

    public class ObjectIdConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(ObjectId);
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType != JsonToken.String)
                throw new Exception($"Unexpected token parsing ObjectId. Expected String, got {reader.TokenType}.");
    
            var value = (string)reader.Value;
            return string.IsNullOrEmpty(value) ? ObjectId.Empty : new ObjectId(value);
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value is ObjectId)
            {
                var objectId = (ObjectId)value;
                writer.WriteValue(objectId != ObjectId.Empty ? objectId.ToString() : string.Empty);
            }
            else
            {
                throw new Exception("Expected ObjectId value.");
            }
        }
    }
    

    2) Register it in JSON.NET globally with global settings and you not need mark you models with big attributes

                var _serializerSettings = new JsonSerializerSettings()
                {
                    Converters = new List { new ObjectIdConverter() }
                };
    

    3) Big advice - don't use ObjectId in your models - use string

    [BsonRepresentation(BsonType.ObjectId]
    public string Id{ get;set; }
    

提交回复
热议问题