Home > Mobile >  Cannot deserialize the JSON object into 'MongoDB.Bson.BsonDocument' type
Cannot deserialize the JSON object into 'MongoDB.Bson.BsonDocument' type

Time:09-26

So I have a JSON file that I want to convert to an object that contains a BsonDocument but I get an error.

My JSON file is:

{
  "words": {
    "wordList": {
      "d": "duck",
      "t": "truck",
      "l": "luck",
      "s": "suck"
    }
  }
}

And I want to be able to deserialize it by doing this:

var contentTest = await File.ReadAllTextAsync("Data/TestConfig.json");
var testresult = JsonConvert.DeserializeObject<TestEntity>(contentTest);

But I get the following:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'MongoDB.Bson.BsonDocument' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. 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. Path 'words.wordList.d', line 4, position 10.

My class TestEntity looks like this:

public class TestEntity
{
    public IDictionary<string, BsonDocument> Words { get; set; }
}

How can I modify my JSON file in order to be able to deserialize those objects into a BsonDocument?

CodePudding user response:

You should use the serializer/deserializer from MongoDB.Bson library instead of Newtonsoft.Json library.

using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Attributes;

var testresult = BsonSerializer.Deserialize<TestEntity>(contentTest);
public class TestEntity
{
    [BsonElement("words")]
    public IDictionary<string, BsonDocument> Words { get; set; }
}

Demo @ .NET Fiddle

  • Related