共用方式為


System.Text.Json 會檢查屬性名稱衝突

在某些情境下,如多態性與參考保存,保留 System.Text.Json 特定屬性名稱(例如 $type、 、 $id$ref)用於發出元資料。 有些屬性名稱,例如 , TypeDiscriminatorPropertyName 也可以設定自訂名稱。 過去,序列化器不會驗證這些屬性名稱是否與使用者定義的合約衝突,這可能導致屬性重複,產生歧義或無法往返的 JSON。 從 .NET 10 開始,System.Text.Json 啟用驗證功能以防止此類設定,並為使用者提供早期警示。

推出的版本

.NET 10

先前的行為

先前,以下程式碼產生了一個無效的 JSON 物件,且有重複 Type 屬性,且無法以以下 JsonException條件反序列化:

using System.Text.Json;
using System.Text.Json.Serialization;

string json = JsonSerializer.Serialize<Animal>(new Dog());
Console.WriteLine(json); // {"Type":"dog","Type":"Dog"}
JsonSerializer.Deserialize<Animal>(json); // JsonException: Deserialized object contains a duplicate 'Type' metadata property.

[JsonPolymorphic(TypeDiscriminatorPropertyName = "Type")]
[JsonDerivedType(typeof(Dog), "dog")]
public abstract class Animal
{
    public abstract string Type { get; }
}

public class Dog : Animal
{
    public override string Type => "Dog";
}

新行為

從 .NET 10 開始,任何嘗試序列化相同類型都會導致早期驗證錯誤:

InvalidOperationException:型別 'Dog' 包含屬性 'Type',與現有的元資料屬性名稱衝突。 考慮用 JsonIgnoreAttribute 重新命名或忽略它。

此驗證錯誤發生在序列化器首次建立或首次嘗試序列化時,能及早偵測無效序列化合約。

破壞性變更的類型

此變更為行為變更

變更的原因

此變更可及早防止無效序列化合約。 透過事先驗證屬性名稱,序列化器可以防止重複屬性的出現,從而避免產生無法正確來回傳輸的無效 JSON。 這有助於開發者在開發過程中識別並修正設定問題,而非在執行時反序列化時才發現。

如需詳細資訊,請參閱:

避免使用與 System.Text.Json 專屬中繼資料屬性(例如 $type$id$ref)衝突的屬性名稱。 如果必須在類別中保留此類屬性,請針對衝突的屬性套用 JsonIgnoreAttribute 註解。

受影響的 API