将字符串转换为MongoDB BsonDocument(续集)

时间:2012-10-26 15:31:29

标签: json mongodb log4net bson appender

我在使用此处建议的方法将{JSON.NET生成的json字符串转换为BsonDocument时遇到了一些问题:Convert string into MongoDB BsonDocument。我正在构建一个MongoDbLog4net appender,它会在mongodb中再次插入LogMessages。这些消息可以包含异常,在某些情况下,异常对象序列化为包含点'的'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);
    }

1 个答案:

答案 0 :(得分: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);
}