鉴于
public class Something
{
[JsonProperty(PropertyName = "Ver")]
public string ver { get; set; }
[JsonProperty(PropertyName = "SomethingElse")]
public object somethingElse { get; set; } // will blow up
// public SomethingElse somethingElse { get; set; } // will not
}
public class SomethingElse
{
[JsonProperty(PropertyName = "uuid")]
public Guid uuid { get; set; }
}
试图序列化然后反序列化Something会将类型为Guid的Unable转换对象抛出到Byte []异常,如果某些东西的成员是对象而不是类型本身。
很抱歉缺乏细节。上面是一个简化的类,您可以序列化但不能反序列化该对象。下面的匹配是更紧密的情况,只有差异是我们需要的字典,这将以完全相同的方式失败。该示例适用于JSOn,而不是BSON。序列化似乎有效,只是反序列化在JSonWriter中抛出异常,无法将类型为'System.Guid'的对象强制转换为'System.Byte []',第552行
case JsonToken.Bytes:
WriteValue((byte[])reader.Value);<-- is trying to case a Guid to byte array
中断;
static void Main(string[] args)
{
const string path = @"C:\zzz_bson.dat";
WriteBson(path);
ReadBson(path);
}
private static void ReadBson(string path)
{
var jsonSerializer = new JsonSerializer();
var file = File.OpenRead(path);
var binaryReader = new BinaryReader(file);
var bsonReader = new BsonReader(binaryReader);
var something = jsonSerializer.Deserialize(bsonReader);
file.Close();
}
private static void WriteBson(string path)
{
//var something = new Dictionary<string, Guid> { { "uuid", new Guid("8afbc8b8-5449-4c70-abd4-3e07046d0f61") } }; //fails
var something = new Dictionary<string, string> { { "uuid", new Guid("8afbc8b8-5449-4c70-abd4-3e07046d0f61").ToString() } }; // works
var jsonSerializer = new JsonSerializer();
var file = File.OpenWrite(path);
var binaryWriter = new BinaryWriter(file);
var bsonWriter = new BsonWriter(binaryWriter);
jsonSerializer.Serialize(bsonWriter, something);
file.Close();
}