当前位置:网站首页>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();
}
}
运行结果如下:
至此,我们成功过滤了所有的只读属性。
边栏推荐
- 【消息通知】用公众号模板消息怎么样?
- 最新 955 不加班的公司名单
- Message queue design based on mysql
- /etc/fstab
- Elastic Stack的介绍
- 怀念故乡的面条
- Make your Lottie support word wrapping in text fields
- [SemiDrive source code analysis] series article link summary (full)
- 软件测试面试(三)
- Flutter Tutorial 02 Introduction to Flutter Desktop Program Development Tutorial Run hello world (tutorial includes source code)
猜你喜欢

【愚公系列】2022年07月 Go教学课程 024-函数
![[Search topic] After reading the inevitable BFS solution to the shortest path problem](/img/f8/fbe906106dc8f7f7a6bd54d2dc3bc1.png)
[Search topic] After reading the inevitable BFS solution to the shortest path problem

怀念故乡的月亮

MLP neural network, GRNN neural network, SVM neural network and deep learning neural network compare and identify human health and non-health data

Open source project site must-have & communication area function

Step by step hand tearing carousel Figure 3 (nanny level tutorial)

Unknown Bounded Array

Hackers can how bad to what degree?

JS new fun(); 类与实例 JS基于对象语言 只能通过书写构造函数充当类

预言机简介
随机推荐
让你的 Lottie 支持文字区域内自动换行
This article takes you to understand the past and present of Mimir, Grafana's latest open source project
带你体验一次类型编程实践
After specifying set 'execution.savepoint.path', restart flinksql and report this error
By CSDN, torn
One service layer needs to call the other two service layers to obtain data and assemble it into the final data. The data is all lists. How to design the cache?
Character encoding and floating point calculation precision loss problem
IJCAI2022 | Hybrid Probabilistic Reasoning with Algebraic and Logical Constraints
The maximum quantity leetcode6133. Grouping (medium)
Unknown Bounded Array
This map drawing tool is amazing, I recommend it~~
一个service层需要调用另两个service层获取数据,并组装成最后的数据,数据都是list,缓存如何设计?
Message queue design based on mysql
Write a method to flatten an array and deduplicate and sort it incrementally
Article summary: the basic model of VPN and business types
August 22 Promotion Ambassador Extra Reward Rules
Flutter Tutorial 02 Introduction to Flutter Desktop Program Development Tutorial Run hello world (tutorial includes source code)
Advice given by experts with four years of development experience in Flutter tutorial
Introduction to the Elastic Stack
HCIP(14)