Newtonsoft.Json使用总结
介绍
Json.NET is a popular high-performance JSON framework for .NET
使用方法
可以在官网或github仓库查看详细文档。在ide中使用时,无需下载代码,在nuget包管理器中搜索即可,或直接using Newtonsoft.Json;,再使用Alt + Enter智能引用
序列化
简单用法:1
JsonConvert.SerializeObject(object? value);
可以创建扩展类方便使用:1
2
3
4public static class NewtonsoftJsonExtension
{
public static string ToJson(this object? value) => JsonConvert.SerializeObject(value);
}
反序列化
简单用法:1
JsonConvert.DeserializeObject<T>(string value);
可以创建扩展类方便使用:1
2
3
4public static class NewtonsoftJsonExtension
{
public static T? FromJsonToObj<T>(this string value) => JsonConvert.DeserializeObject<T>(value);
}
返回Json时日期格式化
示例
dto类中的属性:1
2
3
4
5
6
7
8/// <summary>
/// 版本生效年月,格式为yyyy-MM
/// 例:"2021-11"
/// </summary>
[]
[]
[]
public DateTime EffectivePeriod { get; set; }
日期格式化类:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16/// <summary>
/// 返回日期格式化类
/// </summary>
public static class ResponseDateFormatter
{
/// <summary>
/// yyyy-MM
/// </summary>
public class YearMonth : IsoDateTimeConverter
{
public YearMonth()
{
DateTimeFormat = "yyyy-MM";
}
}
}
说明
通过继承IsoDateTimeConverter,然后在ctor中对DateTimeFormat属性赋值格式化字符串,之后可以在序列化时需要格式化的DateTime类型的属性上加上[JsonConverter()]特性,参数为typeof(继承类)
