我已經實作了這個(相當老的)問題的答案https://stackoverflow.com/a/31732029/4180176但它似乎對我不起作用,我不知道為什么。
我確實可以看到它property.Writable
被設定為 false。我標記為不可序列化的屬性被放置為輸出 json 中的最后一個欄位,但始終存在
啟動.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; }
}
uj5u.com熱心網友回復:
序列化
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
班級
public partial class LeaderboardUser
{
public string UserID { get; set; }
public string UserName { get; set; }
[JsonConstructor]
public LeaderboardUser(string UserId)
{
}
public LeaderboardUser()
{
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/474278.html
上一篇:清單清除后如何保留我的課程