【发布时间】:2012-10-26 15:31:29
【问题描述】:
我在使用此处建议的方法将 JSON.NET 生成的 json 字符串转换为 BsonDocument 时遇到一些问题:Convert string into MongoDB BsonDocument。我正在构建一个 MongoDbLog4net 附加程序,它将 LogMessages 插入 mongodb。这些消息可能包含异常,并且在某些情况下,异常对象会序列化为包含点 '.' 的 json 字符串。在一些导致 BsonSerializer.Desrialize 方法抱怨的键中。有没有一种简单/有效的方法来告诉 JsonConvert 不要用其他东西放置或替换无效字符?
protected override void Append(LoggingEvent loggingEvent)
{
// the log message here is used to filter and collect the
// fields from loggingEvent we are interested in
var logMessage = new LogMessage(loggingEvent);
// since mongodb does not serialize exceptions very well we
// will use JSON.NET to serialize the LogMessage instance
// and build the BSON document from it
string jsonLogMessage = JsonConvert.SerializeObject(logMessage);
var bsonLogMessage = BsonSerializer.Deserialize<BsonDocument>(jsonLogMessage);
this.logCollection.Insert(bsonLogMessage);
}
【问题讨论】:
-
如果反序列化程序在有效的 json 文档上失败,请在 jira.mongodb.org 上为 C# 驱动程序提交错误报告,并附上一个简单的示例,以便我们重现。
-
这不是反序列化器的错误,只是你们不允许将 {"Key.with.points": "Value"} 之类的东西转换为 BsonDocument。我在某处读过'。 BsonDocument 的键中不允许使用和 '$'。
标签: json mongodb log4net bson appender