C#Driver将mongodb数据读取到类型对象上的时候,转换json对象过程出现了objectid字段无法正常转换为字符串的现象(取而代之的是objectid的每个字符+换行符)
stackoverflow里面有个答案使用了特性的解决办法:
在ObjectId字段上添加jsonconvert特性,该特性继承于JsonConverter抽象类型
重写了改类型的序列化(WriteJson)和反序列化(ReadJson)两个函数
具体例子如下:
public class UserItem
{
[JsonConverter(typeof(ObjectIdConverter))]
public ObjectId _id { get; set; }
}
class ObjectIdConverter : JsonConverter
{
//重写序列化
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value.ToString());
}
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.get{reader.TokenType}");
}
var value = (string) reader.Value;
return string.IsNullOrEmpty(value) ? ObjectId.Empty : ObjectId.Parse(value);
}
//重新反序列化
public override bool CanConvert(Type objectType)
{
return typeof(ObjectId).IsAssignableFrom(objectType);
}
}
参考链接:JSON.NET cast error when serializing Mongo ObjectId