1

I have some problems converting JSON.NET generated json string to BsonDocument using the method that is suggested here: Convert string into MongoDB BsonDocument. I am bulding a MongoDbLog4net appender which inserts LogMessages againt the mongodb. Those messages can contain exceptions and in some cases the exception object serializes to json string that contains points '.' in some keys causing the BsonSerializer.Desrialize method to complain. Is there an easy/efficient way to tell JsonConvert to not put or replace invalid characters with something else?

    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);
    }
Community
  • 1
  • 1
Mihail Shishkov
  • 14,129
  • 7
  • 48
  • 59
  • IF the deserializer is failing on a valid json document, then please file a bug report at jira.mongodb.org for the C# driver with a simple example so we can reproduce. – Craig Wilson Oct 26 '12 at 15:53
  • Its not a bug of the Deserializer its just that you guys do not allow something like that {"Key.with.points": "Value"} to be converted to BsonDocument. I've read somewhere that '.' and '$' are not allowed in keys of BsonDocument. – Mihail Shishkov Oct 26 '12 at 16:07

1 Answers1

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);
}
David Sulpy
  • 2,277
  • 2
  • 19
  • 22
  • Of course, the only downside to this is that not only are your keys going to get transformed, but your values are going to be transformed as well. However, I don't think that trade off is too bad.. but that's up to the implementer. :) – David Sulpy Apr 30 '14 at 14:36