Converting from JSON to BsonDocument in mongodb-csharp-driver

133 views
Skip to first unread message

djMax

unread,
Nov 17, 2010, 10:13:11 AM11/17/10
to mongodb-user
Is it currently possible to convert from JSON to a BsonDocument in the
mongodb-csharp-driver? Would make it a bit easier for me to store
results of web services that return JSON.

Robert Stam

unread,
Nov 17, 2010, 10:20:02 AM11/17/10
to mongodb-user
Not in v0.7. It is on the to-do list (priority undecided but not the
highest right now).

djMax

unread,
Nov 17, 2010, 12:01:20 PM11/17/10
to mongodb-user
When you get there I've noticed two painful things: 1, the built in
JSON deserializer likes decimal, Bson not so much. 2 is that it also
uses ArrayList sometimes, not sure why. So I modified BsonTypeMapper
to handle IEnumerable (since that is essentially IEnumerable<object>
anyway). Diff attached.

diff --git a/Bson/ObjectModel/BsonTypeMapper.cs b/Bson/ObjectModel/
BsonTypeMapper.cs
index 6d24106..f02ff64 100644
--- a/Bson/ObjectModel/BsonTypeMapper.cs
+++ b/Bson/ObjectModel/BsonTypeMapper.cs
@@ -157,6 +157,10 @@ namespace MongoDB.Bson {
if (value is IEnumerable<object>) {
return new BsonArray((IEnumerable<object>)
value);
}
+ else if (value is IEnumerable)
+ {
+ return new BsonArray(((IEnumerable)value).Cast<object>());
+ }
break;
case BsonType.Document:
if (value is IDictionary<string, object>) {
@@ -188,10 +200,16 @@ namespace MongoDB.Bson {
bsonValue = new BsonArray((IEnumerable<object>)
value);
return true;
}
- if (value is IDictionary<string, object>) {
+ if (value is IDictionary<string, object>)
+ {
bsonValue = new BsonDocument((IDictionary<string,
object>) value);
return true;
}
+ if (value is IEnumerable)
+ {
+ bsonValue = new
BsonArray(((IEnumerable)value).Cast<object>());
+ return true;
+ }

bsonValue = null;
return false;
Reply all
Reply to author
Forward
0 new messages