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,号称性能更好,今天抽空就来捣鼓一下. 使用起 ...
随机推荐
- Normalizing flow 流模型 | CS236深度生成模型Lec8学习笔记
主要参考资料:Stanford University CS236: Deep Generative Models Lec8. 这篇blog基本上是CS236 Lec8的刷课总结/刷课笔记. VAE 这 ...
- Vuex:让状态管理不再头疼的“管家”
如果你正在开发一个 Vue.js 应用程序,但发现自己被各种组件之间的状态共享问题搞得焦头烂额,那么 Vuex 就是你需要的"超级管家".Vuex 是专门为 Vue.js 设计的状 ...
- 《空间三角面片对相交判断算法》的matlab实现_ 0.2微秒
function [flag] = InsectTriPatch(T1,T2) % 判断两个空间三角形面片是否相交 % T1=[0 0 0; % 2 0 0; % 0 1.5 0; % 0 0 1]; ...
- C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
前言 C#/.NET/.NET Core技术前沿周刊,你的每周技术指南针!记录.追踪C#/.NET/.NET Core领域.生态的每周最新.最实用.最有价值的技术文章.社区动态.优质项目和学习资源等. ...
- [python]pip换源详解
[python]pip换源详解 前言 现有的各个网站上的pip换源方式,很零散,或者是很单调的重复,又或者只是给出命令,尽管这通常就够用了. 但是,我希望汇总一下,然后再结合pip的官方文档来做一 ...
- python包管理工具pip使用手册
pip是什么? pip 是 Python 标准库管理器,也就是一个工具让你安装不同的类库来使用. 当你要安装某些类库时,都会使用 pip,那 pip 除了安装类库之外,还能做什么呢? 首先,我们进入 ...
- mongodb logical sessions can't have multiple authenticated users
前言 使用 mongodb db.auth,切换用户时,报以下错误 logical sessions can't have multiple authenticated users 原因是 mongo ...
- 业余无线电之配置Orbitron My DDE 自动推送多普勒频率至SDRSharp程序中
配置Orbitron My DDE 推送多普勒频率至SDR (By:BI8EJM) Start Edit Time 2021/8/16 23:03 要实现的功能:通过本次设置,让Orbitron程序自 ...
- 3.14 + 1e10 - 1e10 = 0 ? ——浮点数的本质
3.14 + 1e10 - 1e10 = 0 ? --浮点数的本质 我们先看这样一个例子: #include <iostream> int main(int argc, char **ar ...
- svelte+vite+ts+melt-ui从0到1完整框架搭建
框架太"重"了:通常一个小型项目只由少数几个简单页面构成,如果使用 Vue 或者 React 这些框架来研发的话,有点"大材小用"了.构建的产物中包含了不少框架 ...