当前位置:网站首页>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();
}
}
运行结果如下:
至此,我们成功过滤了所有的只读属性。
边栏推荐
- second uncle
- 剑指offer专项突击版第16天
- 【愚公系列】2022年07月 Go教学课程 024-函数
- Introduction to Oracle
- SQL Analysis of ShardingSphere
- Flutter Tutorial 02 Introduction to Flutter Desktop Program Development Tutorial Run hello world (tutorial includes source code)
- lambda
- Message Queuing Message Storage Design (Architecture Camp Module 8 Jobs)
- 2. # 代码注释
- 初出茅庐的小李第114篇博客项目笔记之机智云智能浇花器实战(3)-基础Demo实现
猜你喜欢

初出茅庐的小李第112篇博客项目笔记之机智云智能浇花器实战(1)-基础Demo实现

出现Command ‘vim‘ is available in the following places,vim: command not found等解决方法

【 Make YOLO Great Again 】 YOLOv1 v7 full range with large parsing (Neck)

MySQL3

Introduction to the Elastic Stack

Unknown Bounded Array

Mysql基础篇(Mysql数据类型)

基于STM32设计的UNO卡牌游戏(双人、多人对战)

Four implementations of
batch insert: have you really got it? 
这个地图绘制工具太赞了,推荐~~
随机推荐
[uniCloud] Application and Improvement of Cloud Objects
使用ts-node报错
纽约大学等 | TM-Vec:用于快速同源检测和比对的模版建模向量
初出茅庐的小李第112篇博客项目笔记之机智云智能浇花器实战(1)-基础Demo实现
深圳某游戏研发公司给每个工位都装监控,网友:堪比坐牢!
Unknown Bounded Array
一个service层需要调用另两个service层获取数据,并组装成最后的数据,数据都是list,缓存如何设计?
Make your Lottie support word wrapping in text fields
Article summary: the basic model of VPN and business types
leetcode6132. Make all elements in an array equal to zero (simple, weekly)
By CSDN, torn
HCIP(15)
软件测试面试(三)
Flutter Tutorial 02 Introduction to Flutter Desktop Program Development Tutorial Run hello world (tutorial includes source code)
Software Testing Interview (3)
初出茅庐的小李第113篇博客项目笔记之机智云智能浇花器实战(2)-基础Demo实现
Passive anti-islanding-UVP/OVP and UFP/OFP passive anti-islanding model simulation based on simulink
MySQL3
HCIP (14)
【uniCloud】云对象的应用与提升