本文介绍了使用Json.NET进行Bson数组(反)序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是尝试使用Json.NET对Bson格式的字符串数组进行序列化和反序列化,但是以下代码失败:

I am simply trying to serialize and deserialize a string array in Bson format using Json.NET, but the following code fails:

var jsonSerializer = new JsonSerializer();
var array = new string [] { "A", "B" };

// Serialization
byte[] bytes;
using (var ms = new MemoryStream())
using (var bson = new BsonWriter(ms))
{
    jsonSerializer.Serialize(bson, array, typeof(string[]));
    bytes = ms.ToArray();
}

// Deserialization
using (var ms = new MemoryStream(bytes))
using (var bson = new BsonReader(ms))
{
    // Exception here
    array = jsonSerializer.Deserialize<string[]>(bson);
}

异常消息:

要解决此错误,可以将JSON更改为JSON数组(例如[1,2,3]),也可以更改反序列化类型,使其成为普通的.NET类型(例如,不是整数之类的原始类型,而不是可以从JSON对象反序列化的集合类型(如数组或List).还可以将JsonObjectAttribute添加到类型中,以强制其从JSON对象反序列化.

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

如何使它正常工作?

推荐答案

在BsonReader上将ReadRootValueAsArray设置为true

Set ReadRootValueAsArray to true on BsonReader

http://james.newtonking. com/projects/json/help/index.html?topic = html/P_Newtonsoft_Json_Bson_BsonReader_ReadRootValueAsArray.htm

此设置是必需的,因为BSON数据规范不会保存有关根值是对象还是数组的元数据.

This setting is required because the BSON data spec doesn't save metadata about whether the root value is an object or an array.

这篇关于使用Json.NET进行Bson数组(反)序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:26