我一直在努力将 MongoDB BSON 文档转换为 c# 中的 List 对象。转换时,我得到以下错误
"{"Unexpected character encountered while parsing value: O. Path '_id', line 1, position 10."}"
在stackoverflow中搜索类似问题后,我发现下面的链接
序列化 Mongo ObjectId 时出现 JSON.NET 转换错误
我也跟着。
我的代码:
示例实体/模型
public class BTMObj
{
[JsonConverter(typeof(MongoDataSerializer))]
public ObjectId _id { get; set; }
public string requestFormat { get; set; }
}
public class MongoDataSerializer : 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(
String.Format("Unexpected token parsing ObjectId. Expected String, got {0}.",
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.");
}
}
}
public List<T> GetMongoCollection<T>(string collectionName)
{
try
{
List<T> list = new List<T>();
var client = new MongoClient(Convert.ToString(ConfigurationManager.AppSettings["MONGO_CONNECTION"]));
var database = client.GetDatabase(Convert.ToString(ConfigurationManager.AppSettings["MONGO_DB"]));
var collection = database.GetCollection<BsonDocument>(collectionName);
var documents = collection.Find(new BsonDocument()).ToList();
foreach (var document in documents)
{
try
{
list.Add(JsonConvert.DeserializeObject<T>(document.ToJson()));
}
catch (Exception ex)
{
}
}
return list;
}
catch (Exception ex)
{
throw;
}
}
调用方法
list = mongoDBOperations.GetMongoCollection<BTMObj>(Collection);
MongoDataSerializer 类覆盖的方法应该被调用,但事实并非如此。我们需要在模型中获取 ObjectId 作为字符串。
请帮助解决此问题。
示例 document.toJson() 值
{
"_id": ObjectId("611cf42e1e4c89336b6fe2f0"),
"requestFormat": "json"
}