C#之System.Text.Json的用法
System.Text.Json 是 C# 中的一个 JSON 序列化和反序列化库,它在 .NET Core 3.0 及更高版本中提供了内置支持。以下是 System.Text.Json 的用法详解:
JSON 序列化
JSON 序列化是将 .NET 对象转换为 JSON 字符串的过程。
using System;
using System.Text.Json;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
var person = new Person
{
Name = "John",
Age = 30
};
string jsonString = JsonSerializer.Serialize(person);
Console.WriteLine(jsonString);
}
}
上述代码中,我们定义了一个 Person 类,然后使用 JsonSerializer.Serialize 方法将 person 对象转换为 JSON 字符串。
反序列化
JSON 反序列化是将 JSON 字符串转换回 .NET 对象的过程。
using System;
using System.Text.Json;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
string jsonString = "{\"Name\":\"John\",\"Age\":30}";
Person person = JsonSerializer.Deserialize<Person>(jsonString);
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
上述代码中,我们使用 JsonSerializer.Deserialize 方法将 JSON 字符串转换为 Person 对象。
高级用法
System.Text.Json 还提供了许多高级选项,以控制序列化和反序列化过程。您可以使用 JsonSerializerOptions 来自定义行为,如命名策略、空值处理、日期时间格式化等。
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true, // 格式化输出
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault,
Converters = { new MyCustomConverter() }
};
string jsonString = JsonSerializer.Serialize(person, options);
自定义转换器
public class MyCustomConverter : JsonConverter<MyType>
{
public override MyType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
// 反序列化逻辑
}
public override void Write(Utf8JsonWriter writer, MyType value, JsonSerializerOptions options)
{
// 序列化逻辑
}
}
然后,将自定义转换器添加到 JsonSerializerOptions 中,如前面的示例所示。
这些是 System.Text.Json 的一些基本用法和高级功能。它提供了一种轻量级且高性能的方式来处理 JSON 数据,适用于序列化和反序列化任务。在开发中,您可以根据需要使用它来与 JSON 数据进行交互。
最后需要注意的是:反序列化是case-sensitive的。
如果要设置为noncase-sensitive:
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
public class CaseInsensitivePropertyConverter<T> : JsonConverter<T>
{
public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.StartObject)
{
using (JsonDocument doc = JsonDocument.ParseValue(ref reader))
{
var root = doc.RootElement;
var obj = Activator.CreateInstance<T>();
foreach (var property in root.EnumerateObject())
{
var propertyName = property.Name;
var propertyValue = property.Value;
var propertyInfo = typeof(T).GetProperty(propertyName, System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
if (propertyInfo != null)
{
object value = JsonSerializer.Deserialize(propertyValue.GetRawText(), propertyInfo.PropertyType);
propertyInfo.SetValue(obj, value);
}
}
return obj;
}
}
throw new JsonException("Expected start of an object.");
}
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, value, options);
}
}
public class QRInfo
{
public string qqrStr { get; set; }
public decimal priwce { get; set; }
}
public class Program
{
public static void Main()
{
var options = new JsonSerializerOptions();
options.Converters.Add(new CaseInsensitivePropertyConverter<QRInfo>());
var testStr = "{\"qqrStr\":\"gkjfdsgjffdsljgfdskljgfdklj",\"priwce\":0.01}";
var qrInfoTest = JsonSerializer.Deserialize<QRInfo>(testStr, options);
Console.WriteLine(qrInfoTest.qqrStr);
Console.WriteLine(qrInfoTest.priwce);
}
}
C#之System.Text.Json的用法的更多相关文章
- [译]试用新的System.Text.Json API
译注 可能有的小伙伴已经知道了,在.NET Core 3.0中微软加入了对JSON的内置支持. 一直以来.NET开发者们已经习惯使用Json.NET这个强大的库来处理JSON. 那么.NET为什么要增 ...
- .NET 5的System.Text.Json的JsonDocument类讲解
本文内容来自我写的开源电子书<WoW C#>,现在正在编写中,可以去WOW-Csharp/学习路径总结.md at master · sogeisetsu/WOW-Csharp (gith ...
- 使用System.Text.Json处理Json文档以及部分坑
System.Text.Json处理Json文档需要用到JsonDocument,JsonElement,JsonProperty. JsonDocument就是一个表示Json文档的东西,JsonE ...
- 在.Net Core 3.0中尝试新的System.Text.Json API
.NET Core 3.0提供了一个名为System.Text.Json的全新命名空间,它支持reader/writer,文档对象模型(DOM)和序列化程序.在此博客文章中,我将介绍它如何工作以及如何 ...
- .netcore3.0 System.Text.Json 日期格式化
.netcore3.0 的json格式化不再默认使用Newtonsoft.Json,而是使用自带的System.Text.Json来处理. 理由是System.Text.Json 依赖更少,效率更高. ...
- In .net 4.8,calculate the time cost of serialization in BinaryFormatter,NewtonSoft.json,and System.Text.Json.JsonSerializer.Serialize
using ConsoleApp390.Model; using Newtonsoft.Json; using System; using System.Collections.Generic; us ...
- C# Serialization performance in System.Runtime.Serialization.Formatters.Binary.BinaryFormatter,Newtonsoft.Json.JsonConvert and System.Text.Json.JsonSerializer.Serialize
In .net core 3.0 using System;using System.Collections.Generic;using System.Collections;using System ...
- .NET Core 内置的 System.Text.Json 使用注意
System.Text.Json 是 .NET Core 3.0 新引入的高性能 json 解析.序列化.反序列化类库,武功高强,但毕竟初入江湖,炉火还没纯青,使用时需要注意,以下是我们在实现使用中遇 ...
- Net core 2.x 升级 3.0 使用自带 System.Text.Json 时区 踩坑经历
.Net Core 3.0 更新的东西很多,这里就不多做解释了,官方和博园大佬写得很详细 关于 Net Core 时区问题,在 2.1 版本的时候,因为用的是 Newtonsoft.Json,配置比较 ...
- .net core中关于System.Text.Json的使用
在.Net Framework的时候序列化经常使用Newtonsoft.Json插件来使用,而在.Net Core中自带了System.Text.Json,号称性能更好,今天抽空就来捣鼓一下. 使用起 ...
随机推荐
- 计数类 dp 做题记录(长期更新)
前言 因为本人太弱,急需锻炼思维,固从现在起开始着手写计数题,并写下题解分析思路的欠缺.另外本文将长时间更新,所以我准备把它置顶,尽量日更! upd on 24.11.6 现版本改成长期更新. P36 ...
- Swagger OpenAPI Schema 为空时 Example Value 显示 "string" 的原因及解决方案
解决Swagger UI示例值显示"string"的问题 最近在使用ObjectScript生成JSON接口文档时,遇到了一个奇怪的问题: 生成的JSON数据是正常的. 但Swag ...
- 自己写的第一个java项目!
项目名为"零钱通" 细节参考 [零基础 快速学Java]韩顺平 零基础30天学会Java 基本版: 1 package project; 2 3 import java.text. ...
- 关于DC1的渗透报告:
打开DC1,发现我们需要登录DC1,但是我们不知道密码,所以我们只能扫描分析一下他的IP地址,在kali中我们用nmap来扫描发现 DC1的IP地址也许是192.168.42.130,我们看看他开了什 ...
- AXUI一个面向设计的UI前端框架,好用
以下是官方介绍: ax的中文意义是:斧子,读音[aeks],取其攻击力强.简单实用之意为本前端框架命名.本团队开发了诸多网站项目,使用了许多常见的前端框架,结合实际项目经验,借鉴了同行的经验,特自主开 ...
- linux ln命令详解
介绍 ln是linux的一个重要命令,它的功能是为某一个文件在另外一个位置建立一个同步的链接.当我们需要在不同的目录,用到相同的文件时,我们不需要在每一个需要的目录下都放一个必须相同的文件,我们只要在 ...
- 汇编概念辨析(Intel/AT&T syntax、GAS、NASM)
写在前面 本文并不详细介绍Intel syntax.AT&T syntax.GAS.NASM的具体内容和具体区别,而是从概念辨析的角度说明这些专有名词的含义,以便为初学者扫清疑惑.有兴趣深入了 ...
- DTMF从2833到inband的方案
概述 freeswitch是一款简单好用的VOIP开源软交换平台. 之前的文章中介绍过通过dialplan拨号计划配置的方法,实现2833到inband的转换,但是实际生产环境中的场景会更复杂,无法预 ...
- 窗体添加按钮--java进阶day03
1.组件.面板对象 窗体中的图片.按钮.文本都是组件,光创建出了窗体没有组件肯定不行,但是这些组件该放到窗体的哪个位置? 很明显是窗体中空白的位置,但是我们需要知道,这块空白位置在窗体中是一个被封装的 ...
- 【Git】工作流
Git 工作流 概念 在项目开发过程中使用 Git 的方式 分类 集中式工作流 像 SVN 一样,集中式工作流以中央仓库作为项目所有修改的单点实体.所有 修改都提交到 Master 这个分支上. 这种 ...