【问题标题】:Convert string into MongoDB BsonDocument (sequel)将字符串转换为 MongoDB BsonDocument(续集)
【发布时间】: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


【解决方案1】:

为什么不对像 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);
}

【讨论】:

  • 当然,唯一的缺点是不仅你的键会被转换,你的值也会被转换。但是,我不认为这种权衡太糟糕了..但这取决于实施者。 :)
猜你喜欢
  • 1970-01-01
  • 2011-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 2015-10-06
相关资源
最近更新 更多