Home > Back-end >  Cannot dynamically create an instance of type 'System.Text.Json.Nodes.JsonObject'. Reason:
Cannot dynamically create an instance of type 'System.Text.Json.Nodes.JsonObject'. Reason:

Time:01-06

Basically, I have this class in my C# project:

 public class Item
 {
     [BsonId]
     public ObjectId Id { get; set; }
     public string AppId { get; set; }

     public JsonObject Fields { get; set; }
 }

And I've created a couple of items in a Mongo DB using a POST request with this body:

{
    "AppId":"(an already existing app id)",
    "Fields":
                {
                    "NombreCliente": "Pepillo",
                    "Email": "[email protected]",
                    "Telefono": "pp56656784",
                    "Localidad": "Pepeland",
                    "Facturas": ["848435498","0564864984"]
                }
    
}

And they were correctly created.

Problem occurs whenever I try to get these items. The error in the tittle pops up:

"(An error occurred while deserializing the Fields property of class divitiae_api.Models.Item: Cannot dynamically create an instance of type 'System.Text.Json.Nodes.JsonObject'. Reason: No parameterless constructor defined.)"

What should I do? I'm really lost here... I've tried creating a parameterless constructor but still keeps failing...

UPDATE

To create an Item I'm using the next method. I can't use a direct "Item" because it throws an exception regarding circular reference in the Field property, so I serialize it to a JSON string and then insert it like that into the collection:


     public async Task InsertItem(JsonObject item)
     {
         var options = new JsonSerializerOptions
         {
             ReferenceHandler = ReferenceHandler.Preserve
         };
         var jsonString = System.Text.Json.JsonSerializer.Serialize(item, options);

         var document = BsonSerializer.Deserialize<BsonDocument>(jsonString);
         var collection2 = _repository.db.GetCollection<BsonDocument>("Items");
         await collection2.InsertOneAsync(document);
        }

And this is the one I'm using to GET them:

     public async Task<List<Item>> GetAllAppItems(string appId)
     {
         var filter = Builders<Item>
             .Filter
             .Eq(s => s.AppId, appId);

         return await Collection.FindAsync(new BsonDocument()).Result.ToListAsync();
      }

CodePudding user response:

Think that MongoDB .NET Driver is unable to know how to map an object to JsonObject as JsonObject is not under its library.

An easy fix is to modify the Fields data type to either object or dynamic.

public class Item
{
    ...

    public dynamic Fields { get; set; }
}
  • Related