当前位置:网站首页>C# | 使用Json序列化对象时忽略只读的属性
C# | 使用Json序列化对象时忽略只读的属性
2022-08-01 03:55:00 【猿长大人】
C# 使用Json序列化对象时忽略只读的属性
前言
将对象序列化成为Json字符串是一个使用频率非常高的功能。Json格式具有很高的可读性,同时相较于XML更节省空间。
在开发过程中经常会遇到需要保存配置的场景,比如将配置信息保存在配置类型的实例中,再将这个对象序列化成为Json字符串并保存。当需要加载配置时,则是读取Json格式的字符串再将其还原成配置对象。在序列化的过程中,默认会将所有公开的属性和字段都序列化进入Json字符串中,这其中也会包含只读的属性或字段,而只读的属性和字段在反序列化的过程中其实是无意义的,也就是说这一部分存储是多余的。
本文将讲解如何在执行Json序列化时,忽略掉那些只读的属性和字段。
示例
修改前
创建一个student类型,包含四个属性,分别是ID,名称,生日和年龄。
其中年龄是根据生日计算得出的,是一个只读的属性。
使用序列化时的默认配置,编代码如下:嗯
public class Student
{
public int Id {
get; set; }
public string Name {
get; set; }
public DateTime Birthday {
get; set; }
public int Age => DateTime.Now.Year - Birthday.Year;
}
internal class Program
{
static void Main(string[] args)
{
Student student = new Student()
{
Id = 1,
Name = "张三",
Birthday = DateTime.Parse("2008-08-08"),
};
Console.WriteLine(JsonConvert.SerializeObject(student,Formatting.Indented));
Console.Read();
}
}
执行结果如下图所示,可以看到,只读的年龄属性也被序列化到了Json字符串中。
修改后
第一步:创建一个用于过滤只读属性的ContractResolver;
第二步:在序列化之前,创建一个Json序列化配置对象,并将刚才编写的ContractResolver放入配置中;
第三步:执行序列化是传入配置对象;
完整代码如下所示:
public class Student
{
public int Id {
get; set; }
public string Name {
get; set; }
public DateTime Birthday {
get; set; }
public int Age => DateTime.Now.Year - Birthday.Year;
}
internal class Program
{
static void Main(string[] args)
{
Student student = new Student()
{
Id = 1,
Name = "张三",
Birthday = DateTime.Parse("2008-08-08"),
};
var settings = new JsonSerializerSettings()
{
ContractResolver = new WritablePropertiesOnlyResolver()
};
Console.WriteLine(JsonConvert.SerializeObject(student, Formatting.Indented, settings));
Console.Read();
}
}
class WritablePropertiesOnlyResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> props = base.CreateProperties(type, memberSerialization);
return props.Where(p => p.Writable).ToList();
}
}
运行结果如下:
至此,我们成功过滤了所有的只读属性。
边栏推荐
- 785. Quick Sort
- 时时刻刻保持敬畏之心
- Flutter "Hello world" program code
- Weekly Summary (*67): Why not dare to express an opinion
- leetcode6132. Make all elements in an array equal to zero (simple, weekly)
- opencv 缩小放大用哪种插值更好??
- button去除黑框
- When opening a MYSQL table, some can display editing, some do not, how to set.
- 故乡的素描画
- Guys, MySQL cdc source recycles replication slave and r in incremental process
猜你喜欢
Which interpolation is better for opencv to zoom in and out??
【uniCloud】云对象的应用与提升
软件测试面试(三)
win10 fixed local IP
Simulation of Active anti-islanding-AFD Active Anti-islanding Model Based on Simulink
win10 固定本机IP
【kali-信息收集】枚举——DNS枚举:DNSenum、fierce
MySQL4
How to promote new products online?
【愚公系列】2022年07月 Go教学课程 023-Go容器之列表
随机推荐
Mysql基础篇(约束)
Dart 命名参数语法
Input input box cursor automatically jumps to the last bug after the previous input
MySQL4
Character encoding and floating point calculation precision loss problem
Unity在BuildIn渲染管线下实现PlanarReflection的初级方法
Article summary: the basic model of VPN and business types
second uncle
IJCAI2022 | Hybrid Probabilistic Reasoning with Algebraic and Logical Constraints
Dynamic Programming 01 Backpack
August 22 Promotion Ambassador Extra Reward Rules
785. Quick Sort
/etc/fstab
对无限debugger的一种处理方式
MySQL4
软件测试周刊(第82期):其实所有纠结做选择的人心里早就有了答案,咨询只是想得到内心所倾向的选择。
Message queue design based on mysql
怀念故乡的面条
Flink 1.13 (8) CDC
[Search topic] After reading the inevitable BFS solution to the shortest path problem