Json 将字符串转换为MongoDB BsonDocument(续集)
使用此处建议的方法将JSON.NET生成的JSON字符串转换为BsonDocument时遇到一些问题:。我正在构建一个MongoDbLog4net附加器,它将日志消息插入mongodb。这些消息可能包含异常,在某些情况下,异常对象序列化为json字符串,该字符串在某些键中包含点“.”,从而导致BsonSerializer.Desrialize方法出现问题。有没有一种简单有效的方法告诉JsonConvert不要放置无效字符或用其他字符替换无效字符Json 将字符串转换为MongoDB BsonDocument(续集),json,mongodb,log4net,bson,appender,Json,Mongodb,Log4net,Bson,Appender,使用此处建议的方法将JSON.NET生成的JSON字符串转换为BsonDocument时遇到一些问题:。我正在构建一个MongoDbLog4net附加器,它将日志消息插入mongodb。这些消息可能包含异常,在某些情况下,异常对象序列化为json字符串,该字符串在某些键中包含点“.”,从而导致BsonSerializer.Desrialize方法出现问题。有没有一种简单有效的方法告诉JsonConvert不要放置无效字符或用其他字符替换无效字符 protected override vo
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);
}
受保护的覆盖无效附加(LoggingEvent LoggingEvent)
{
//此处的日志消息用于筛选和收集
//我们感兴趣的loggingEvent中的字段
var logMessage=新的logMessage(loggingEvent);
//因为mongodb不能很好地序列化异常,所以我们
//将使用JSON.NET序列化LogMessage实例
//并从中构建BSON文档
字符串jsonLogMessage=JsonConvert.SerializeObject(logMessage);
var bsonLogMessage=BsonSerializer.Deserialize(jsonLogMessage);
this.logCollection.Insert(bsonLogMessage);
}
为什么不在像StringBuilder这样的可变字符串上替换一个简单的字符串呢
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
StringBuilder jsonLogMessageStringBuilder = new StringBuilder(JsonConvert.SerializeObject(logMessage));
var jsonLogMessage = jsonLogMessageStringBuilder.Replace(".", "_").ToString();
var bsonLogMessage = BsonSerializer.Deserialize<BsonDocument>(jsonLogMessage);
this.logCollection.Insert(bsonLogMessage);
}
受保护的覆盖无效附加(LoggingEvent LoggingEvent)
{
//此处的日志消息用于筛选和收集
//我们感兴趣的loggingEvent中的字段
var logMessage=新的logMessage(loggingEvent);
//因为mongodb不能很好地序列化异常,所以我们
//将使用JSON.NET序列化LogMessage实例
//并从中构建BSON文档
StringBuilder jsonLogMessageStringBuilder=新的StringBuilder(JsonConvert.SerializeObject(logMessage));
var jsonLogMessage=jsonLogMessageStringBuilder.Replace(“.”,“”).ToString();
var bsonLogMessage=BsonSerializer.Deserialize(jsonLogMessage);
this.logCollection.Insert(bsonLogMessage);
}
如果反序列化程序在一个有效的json文档上失败,那么请在jira.mongodb.org上为C#driver提交一份错误报告,并提供一个简单的示例,以便我们可以重现。这不是反序列化程序的错误,只是你们不允许将类似{“Key.with.points”:“Value”}的东西转换为BsonDocument。我在某个地方读到过,BsonDocument的键中不允许使用“.”和“$”。当然,唯一的缺点是,不仅您的键会被转换,而且您的值也会被转换。然而,我不认为这种权衡太糟糕。。但这取决于实施者。:)