[英].NET Newtonsoft Allow property to be only serialised
I have implemented the answer from this (rather old) question https://stackoverflow.com/a/31732029/4180176 but it doesn't seem to work for me and I can't figure out why.我已经实现了这个(相当老的)问题的答案https://stackoverflow.com/a/31732029/4180176但它似乎对我不起作用,我不知道为什么。
I can indeed see that property.Writable
gets set to false.我确实可以看到
property.Writable
设置为 false。 The property I mark as not serializable gets put as the last field in the output json but is always present我标记为不可序列化的属性被放置为输出 json 中的最后一个字段,但始终存在
Startup.cs启动.cs
services.AddControllers().AddNewtonsoftJson(opt =>
{
opt.UseMemberCasing();
opt.SerializerSettings.ContractResolver = new NewtonsoftContractResolver();
});
Contract Resolver合约解析器
[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;
}
}
Attribute Usage属性使用
public class LeaderboardUser : RankedObject
{
[JsonProperty("UserID")]
[DoNotSerialize]
public string UserID { get; set; }
}
serialization序列化
var leaderBoardUser = new LeaderboardUser { UserID = "userId", UserName = "userName" };
var json = JsonConvert.SerializeObject(leaderBoardUser);
result结果
{"UserID":"userId","UserName":"userName"}
deserialization反序列化
leaderBoardUser = JsonConvert.DeserializeObject<LeaderboardUser>(json);
result结果
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()
{
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.