简体   繁体   English

从BSON序列化为JSON

[英]Serialize to JSON from BSON

I'm trying to serialize some BSON returned from MongoDB into JSON: 我正在尝试将从MongoDB返回的一些BSON序列化为JSON:

var bson = MongoDB.Bson.BsonDocument.Parse(@"{
    ""_id"": ObjectId(""5a45a64ec7fe121dfc673c6f""),
    ""MyOtherId"": ObjectId(""5a45a64dc7fe121dfc673c6e""),
    ""Blah"": ""Test""
}");

And I want to morph the ObjectID into a string so I get 而且我想将ObjectID转换为字符串,以便得到

"_id": "5a45a64ec7fe121dfc673c6f",

instead of 代替

"_id": {"$oid": "5a4597a3d999f209e05df993"},

so I tried this: 所以我尝试了这个:

var result = Newtonsoft.Json.JsonConvert.SerializeObject(bson, new Newtonsoft.Json.Bson.Converters.BsonDataObjectIdConverter());

But I get an error: 但是我得到一个错误:

Newtonsoft.Json.JsonSerializationException: 'Error getting value from 'AsBoolean' on 'MongoDB.Bson.BsonObjectId'.' Newtonsoft.Json.JsonSerializationException:'从'MongoDB.Bson.BsonObjectId'上的'AsBoolean'获取值时出错。

Inner exception: InvalidCastException: Unable to cast object of type 'MongoDB.Bson.BsonObjectId' to type 'MongoDB.Bson.BsonBoolean'. 内部异常:InvalidCastException:无法将类型为“ MongoDB.Bson.BsonObjectId”的对象转换为类型为“ MongoDB.Bson.BsonBoolean”的对象。

I still get the error with the simplified version: 简化版本仍然出现错误:

var result = Newtonsoft.Json.JsonConvert.SerializeObject(bson);

using Newtonsoft.Json v10.0.3 and MongoDB.Driver v2.5.0 使用Newtonsoft.Json v10.0.3和MongoDB.Driver v2.5.0

Newtonsoft tries to read every property of an object into a Json value. Newtonsoft尝试将对象的每个属性读入Json值。 So if your object has public string Lol {get { throw new Exception}} , Newtonsoft will try to read Lol , get the exception, and will fail serializing. 因此,如果您的对象具有public string Lol {get { throw new Exception}} ,Newtonsoft将尝试读取Lol ,获取异常,并且序列化失败。

Now, a Bson value has lots of properties like AsBoolean , AsString , which throw an exception if the actual value isn't what they expect. 现在,Bson值具有许多属性,例如AsBooleanAsString ,如果实际值不是他们期望的值, AsString抛出异常。 Mongo expects you to know what value is contained in the bson and access the appropriate proeprty. Mongo希望您知道bson中包含什么值并访问适当的属性。 But since Newtonsoft tries to access all properties, you get that error. 但是由于Newtonsoft尝试访问所有属性,因此您会收到该错误。

You can work around that issue by writing a custom converter for BsonValue and passing it to Newtonsoft in the SerializationSettings. 您可以通过为BsonValue编写自定义转换器并将其传递给SerializationSettings中的Newtonsoft来解决此问题。 Your converter will need to call getBsonType() on the VsonValue, and then the correct AsBoolean , AsInt or whatever to get the actual value. 您的转换器将需要在getBsonType()上调用getBsonType() ,然后调用正确的AsBooleanAsInt或任何其他方法来获取实际值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM