![](/img/trans.png)
[英]Serialize and deserialize custom type using Newtonsoft.Json without attributes
[英]Custom JsonConverter attributes not working with Json.Serialize() using Newtonsoft.JSON in ASP.NET Core 3.1
我想使用 Newtonsoft Json.NET 在 ASP.NET Core 3.1 應用程序中執行反/序列化。 我在啟動 ConfigureServices 代碼中添加了以下內容:
services.AddMvc().AddNewtonsoftJson();
我有一個帶有自定義序列化屬性的 MVC 模型:
public class MyModel {
[Newtonsoft.Json.JsonConverter(typeof(MyCustomJsonConverter))]
public DateTime MyProperty {get; set;}
}
在我看來,我將其序列化為 JSON:
<script>
someJsFunction(@Json.Serialize(Model));
</script>
但它不使用 MyCustomJsonConverter。 MyCustomJsonConverter 中未命中斷點。
一個答案可能是添加到全局 Json 設置中:
services.AddMvc().AddNewtonsoftJson(options =>
{
options.SerializerSettings.Converters = new List<JsonConverter>()
{
new MyCustomJsonConverter()
};
});
但是隨后 MyCustomJsonConverter 應用於每個 DateTime 屬性,而不僅僅是應用了該屬性的屬性。 我也可以使用 JSON.Serialize 重載:
<script>
someJsFunction(@Json.Serialize(Model, new JsonSerializerSettings()
{
Converters = new List<JsonConverter> { new MyCustomJsonConverter()},
}
));
</script>
但我不想每次調用它時都這樣做。 我很確定這些 JsonConverter 屬性在從 3.0 中的 Newtonsoft Json.NET 切換之前自己工作得很好。 任何想法我做錯了什么?
在您的視圖中為 Newtonsoft 添加 using 並使用其序列化程序。
@using Newtonsoft.Json;
...
..(@JsonConvert.SerializeObject(Model))
不起作用的原因是您使用的是來自不同庫的序列化程序,一個來自Microsoft.AspNetCore.Mvc.Rendering
,另一個來自Newtonsoft.Json
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.