Dotnet API 错误类型 System.Text.Json.JsonElement 未配置为允许为此 ObjectSerializer 实例序列化的类型

Dotnet API Error Type System.Text.Json.JsonElement is not configured as a type that is allowed to be serialized for this instance of ObjectSerializer

提问人:Chirag 提问时间:11/15/2023 最后编辑:Brian Tompsett - 汤莱恩Chirag 更新时间:11/15/2023 访问量:40

问:

我使用 Dotnet Core API 和 MongoDB 作为我的数据库。 我正在尝试为一个集合创建一个简单的 CURD 操作。 API 的 Get 方法工作正常,但我收到 Post 调用错误。我尝试了几个可用的选项,但似乎没有任何效果。

错误如下

MongoDB.Bson.BsonSerializationException:序列化类 Datasparkx_Model.AdminForm.AdminFormModel 的 Metadata 属性时出错:类型 System.Text.Json.JsonElement 未配置为允许为此 ObjectSerializer 实例序列化的类型。

模型类 =>

public class MyModel
{
  [BsonId]
  [BsonRepresentation(BsonType.ObjectId)]
  public string? Id { get; set; }
  
  public Object[] Testdata { get; set; }
}

控制器调用 =>

[HttpPost(Name = "AddData")]
public async Task<bool> Post(MyModel document)
{
    await _myCollection.InsertOneAsync(document);
}

Javascript 调用

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  "testData": [
    {
      "data1": "name",
      "data2": "textfield",
      "data3": true
    },
    {
      "data1": "email",
      "data3": "email",
      "data4": true
    },
    {
      "randomData": "address",
      "newData": false,
      "anyData": "textarea"
    }
  ]
});

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("https://localhost:7051/AddData", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

参数在控制器级别按预期正确传递,但它没有在我的数据库中添加任何数据并引发上述错误。

有人可以指导我,因为我是MongoDB的新手。

C# asp.net MongoDB ASP.net-core-webapi

评论


答:

1赞 Yong Shun 11/15/2023 #1

当您声明 as 类型时:TestdataObject[]

public Object[] Testdata { get; set; }

当反序列化请求数据时,默认情况下将定义 中的对象。MongoDB .NET Driver / 不支持(反)序列化 .JsonSerializerTestdataJsonElementBsonSerializerJsonElement

也:

  1. 是否有额外的实现可以转换为 @dbc 的答案 如何有效地将 JsonElement 转换为 BsonDocument?JsonElementBsonElement

  2. 序列化 via 并使用 进行反序列化。documentSystem.Text.Json.JsonSerializerMongoDB.Bson.Serialization.BsonSerializer

请注意,使用此方法时,应排除反序列化,以防止在模型类中找不到错误。或者,您可以将该属性应用于类。IdId[BsonIgnoreExtraElements]MyModel

using System.Text.Json;
using System.Text.Json.Serialization;
using MongoDB.Bson.Serialization;

string serializedJson = JsonSerializer.Serialize(document, new JsonSerializerOptions
{
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
});

document = BsonSerializer.Deserialize<MyModel>(json);
await _collection.InsertOneAsync(document);

演示

enter image description here