当前位置:网站首页>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();
}
}
运行结果如下:
至此,我们成功过滤了所有的只读属性。
边栏推荐
- Open source project site must-have & communication area function
- 故乡的素描画
- win10 fixed local IP
- leetcode:126. Word Solitaire II
- 一个往年的朋友
- After specifying set 'execution.savepoint.path', restart flinksql and report this error
- 项目越写越大,我是这样做拆分的
- 【SemiDrive源码分析】系列文章链接汇总(全)
- 【无标题】
- The kernel's handling of the device tree
猜你喜欢
《少年派2》:新男友竟脚踩两只船,林妙妙与钱三一感情回温
出现Command ‘vim‘ is available in the following places,vim: command not found等解决方法
软件测试面试(三)
使用ts-node报错
Error using ts-node
【无标题】
IJCAI2022 | Hybrid Probabilistic Reasoning with Algebraic and Logical Constraints
初出茅庐的小李第114篇博客项目笔记之机智云智能浇花器实战(3)-基础Demo实现
Introduction to the Elastic Stack
Open source project site must-have & communication area function
随机推荐
button remove black frame
Difference Between Compiled and Interpreted Languages
After specifying set 'execution.savepoint.path', restart flinksql and report this error
博客系统(完整版)
【搜索专题】看完必会的BFS解决最短路问题攻略
Simple and easy to use task queue - beanstalkd
时时刻刻保持敬畏之心
The maximum quantity leetcode6133. Grouping (medium)
win10 fixed local IP
情人节浪漫3D照片墙【附源码】
TypeScript简化运行之ts-node
深圳某游戏研发公司给每个工位都装监控,网友:堪比坐牢!
PMP 项目沟通管理
lua entry case combat 123DIY
软件测试基础理论知识—用例篇
Which interpolation is better for opencv to zoom in and out??
The fledgling Xiao Li's 112th blog project notes: Wisdom cloud intelligent flower watering device actual combat (1) - basic Demo implementation
Simulation of Active anti-islanding-AFD Active Anti-islanding Model Based on Simulink
Take you to experience a type programming practice
Make your Lottie support word wrapping in text fields