.NET Newtonsoft 允许 属性 只被序列化

.NET Newtonsoft Allow property to be only serialised

我已经实现了这个(相当老的)问题的答案 但它似乎对我不起作用,我也不知道为什么。

我确实可以看到 property.Writable 被设置为 false。我标记为不可序列化的 属性 被作为输出中的最后一个字段 json 但始终存在

Startup.cs

services.AddControllers().AddNewtonsoftJson(opt =>
{
  opt.UseMemberCasing();
  opt.SerializerSettings.ContractResolver = new NewtonsoftContractResolver();
});

合约解析器

[AttributeUsage(AttributeTargets.Property)]
public class DoNotSerializeAttribute : Attribute
{

}

public class NewtonsoftContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);

        if (property is not null && property.Writable)
        {
            var attributes = property.AttributeProvider.GetAttributes(typeof(DoNotSerializeAttribute), true);

            if (attributes is not null && attributes.Count > 0)
            {
                    property.Writable = false;
            }
        }    
        return property;
    }
}

属性用法

public class LeaderboardUser : RankedObject
{
    [JsonProperty("UserID")]
    [DoNotSerialize]
    public string UserID { get; set; }
}

序列化

var leaderBoardUser = new LeaderboardUser { UserID = "userId", UserName = "userName" };
var json = JsonConvert.SerializeObject(leaderBoardUser);

结果

{"UserID":"userId","UserName":"userName"}

反序列化

leaderBoardUser = JsonConvert.DeserializeObject<LeaderboardUser>(json);

结果

UserID  null
UserName    userName

class

public partial class LeaderboardUser
{
    public string UserID { get; set; }
    public string UserName { get; set; }

    [JsonConstructor]
    public LeaderboardUser(string UserId)
    {

    }
    public LeaderboardUser()
    {

    }
}