【发布时间】:2021-10-05 07:40:06
【问题描述】:
我一直在努力将 MongoDB BSON 文档转换为 C# 中的 List 对象。 转换时,我得到以下错误
"{"Unexpected character encountered while parsing value: O. Path '_id', line 1, position 10."}"
在stackoverflow中搜索了类似的问题后,我找到了下面的链接
JSON.NET cast error when serializing Mongo ObjectId
我也照做了。
我的代码:
示例实体/模型
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 类重写的方法应该被调用,但事实并非如此。 我们需要在 Model 中获取 ObjectId 作为字符串。
请帮忙解决这个问题。
示例 document.toJson() 值
{
"_id": ObjectId("611cf42e1e4c89336b6fe2f0"),
"requestFormat": "json"
}
【问题讨论】:
-
请分享
document.ToJson()的值 -
@viveknuna - 添加了 document.ToJson() 值
标签: c# mongodb-query json.net mongodb-.net-driver newtonscript