簡體   English   中英

反序列化 Bson 文件

[英]Deserialize Bson file

我有一個使用 mongodump 工具生成的 Bson 文件。 我想在 C# 代碼中反序列化。 為此,我似乎可以使用 mongodb C# 驅動程序或 Json.net 庫。 我嘗試了他們兩個,但我無法讓他們工作。

使用Json.net庫:“input”是Bson文件的路徑

JsonSerializer serializer = new JsonSerializer();
BsonReader reader = new BsonReader(File.OpenRead(input));
serializer.Deserialize<List<Json.Profil>>(reader);

在 Deserialize() 上,出現以下異常:

無法將當前的 JSON object(例如 {"name":"value"})反序列化為類型 'System.Collections.Generic.List`1[Moul.netteConsole.Json.Profil]' 因為該類型需要一個 881569900 [78588 數組1,2,3]) 正確反序列化。

要修復此錯誤,請將 JSON 更改為 JSON 數組(例如 [1,2,3])或更改反序列化類型,使其成為正常的 .NET 類型(例如,不是像 integer 這樣的原始類型,不是像array or List),可以從 JSON object 反序列化。JsonObjectAttribute 也可以添加到類型以強制它從 JSON object 反序列化。

[編輯]如果使用工具 bsondump 將 bson 導出到 json 文件,我得到:

{ "id" : "1",
  "value" : { "foo" : null, "bar" : "test"}
}
{ "id" : "2",
  "value" : { "foo" : null, "bar" : "test"}
}

此外,如果我更換:

serializer.Deserialize<List<Json.Profil>>(reader);

經過

serializer.Deserialize<Json.Profil>(reader);

我不再得到異常,但我只檢索集合的第一條記錄。

終於找到了答案。 假設您正在反序列化 Animals 並且您的 c# 代碼中有一個 class Animal 可以正確映射到您正在反序列化的內容。 在這種情況下,此代碼將起作用:

運行此命令以確保您有一個 bson 文件:

mongodump --db=MyDatabase --collection=Animals --out=/tmp/output 

然后將bson生成的文件導入為:

var path = "/tmp/output/MyDatabase/Animals.bson";

using var fileStream = File.OpenRead(path);
FileInfo fi = new FileInfo(path);
var size = fi.Length;
while (fileStream.Position<size)
{
    var animal = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<Animal>(fileStream);
    Console.WriteLine(animal.Name);
}

您的文件可能包含如下所示的Json

{
    "foo":1,
    "bar":"baz"
}

但是通過嘗試反序列化為List<> ,反序列化程序期望

[{
    "foo":1,
    "bar":"baz"
},
{
    "foo":2,
    "bar":"baz"
},
...]

只需將反序列化線更改為:

serializer.Deserialize<Json.Profil>(reader);

應該管用。

這是錯誤告訴您的內容:

無法反序列化當前JSON對象(例如{“ name”:“ value”})為類型'System.Collections.Generic.List`1 [MoulinetteConsole.Json.Profil]',因為該類型需要JSON數組(例如[1, 2,3])正確反序列化。

要解決此錯誤,可以將JSON更改為JSON數組(例如[1,2,3]),也可以更改反序列化類型,使其成為普通的.NET類型 (例如,不像整數這樣的原始類型,也不像這樣的集合類型)數組或List ),可以從JSON對象反序列化。 還可以將JsonObjectAttribute添加到類型中,以強制其從JSON對象反序列化。

嘗試設置BSON Reader的屬性-ReadRootValueAsArray = true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM