使属性反序列化但不使用json.net序列化

我们有一些配置文件,这些文件是通过使用Json.net序列化C#对象而生成的。

我们希望将序列化类的一个属性从简单的枚举属性迁移到类属性。

一种简单的方法是将旧的enum属性保留在类上,并安排Json.net在加载配置时读取此属性,但在下次序列化对象时不再保存它。我们将处理从旧枚举分别生成新类的问题。

有没有简单的方法来标记(例如,带有属性)C#对象的属性,以便Json.net仅在序列化时将其忽略,而在反序列化时将对其进行关注?


慕尼黑的夜晚无繁华
浏览 478回答 3
3回答

慕姐4208626

我喜欢在这个属性上坚持使用属性,这是在需要反序列化属性但不序列化属性时使用的方法,反之亦然。第1步-创建自定义属性public class JsonIgnoreSerializationAttribute : Attribute { }第2步-创建自定义合同转帐class JsonPropertiesResolver : DefaultContractResolver{&nbsp; &nbsp; protected override List<MemberInfo> GetSerializableMembers(Type objectType)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //Return properties that do NOT have the JsonIgnoreSerializationAttribute&nbsp; &nbsp; &nbsp; &nbsp; return objectType.GetProperties()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.Where(pi => !Attribute.IsDefined(pi, typeof(JsonIgnoreSerializationAttribute)))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.ToList<MemberInfo>();&nbsp; &nbsp; }}步骤3-在不需要序列化但反序列化的地方添加属性&nbsp; &nbsp; [JsonIgnoreSerialization]&nbsp; &nbsp; public string Prop1 { get; set; } //Will be skipped when serialized&nbsp; &nbsp; [JsonIgnoreSerialization]&nbsp; &nbsp; public string Prop2 { get; set; } //Also will be skipped when serialized&nbsp; &nbsp; public string Prop3 { get; set; } //Will not be skipped when serialized第4步-使用它var sweet = JsonConvert.SerializeObject(myObj, new JsonSerializerSettings { ContractResolver = new JsonPropertiesResolver() });希望这可以帮助!同样值得注意的是,当反序列化发生时,这也会忽略属性,当我进行反序列化时,我只是以常规方式使用转换器。JsonConvert.DeserializeObject<MyType>(myString);
打开App,查看更多内容
随时随地看视频慕课网APP