2012-10-26 76 views
1

我有一些问题转换JSON.NET生成的json字符串到BsonDocument使用这里建议的方法:Convert string into MongoDB BsonDocument。我正在构建一个MongoDbLog4net appender,它将mongodb再次插入LogMessages。这些消息可以包含异常,并且在某些情况下,异常对象序列化为包含点'。'的json字符串。在某些键导致BsonSerializer.Desrialize方法投诉。有没有一种简单/有效的方式来告诉JsonConvert不要将无效字符置换或替换为其他字符?将字符串转换为MongoDB BsonDocument(续集)

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); 
    } 
+0

IF解串器是在一个有效的JSON文件失败,那么请提交在jira.mongodb.org bug报告用一个简单的例子C#的驱动程序,以便我们可以重现。 –

+0

它不是反序列化程序的错误,只是你们不允许像这样{{Key.with.points':“Value”}被转换为BsonDocument。我在某处读过''。和'$'不允许在BsonDocument的键中。 –

回答

0

为什么不用简单的字符串替换像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); 
} 
+0

当然,唯一的缺点是,你的钥匙不仅会变形,而且你的价值观也会随之变化。但是,我并不认为这种交易太糟糕了,但这取决于实施者。 :) –