1

我在使用此处建议的方法将 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);
    }
4

1 回答 1

0

Why not a simple string replace on a mutable string like 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);
}
于 2014-04-30T14:28:34.043 回答