如何使用 C# 对 JSON 数据进行序列化和反序列化 您所在的位置:网站首页 json字符串转jsonobject对象 如何使用 C# 对 JSON 数据进行序列化和反序列化

如何使用 C# 对 JSON 数据进行序列化和反序列化

2023-09-15 03:09| 来源: 网络整理| 查看: 265

如何在 .NET 中对 JSON 数据进行序列化和反序列化 项目 08/01/2023

本文演示如何使用 System.Text.Json 命名空间向/从 JavaScript 对象表示法 (JSON) 进行序列化和反序列化。 如果要从 Newtonsoft.Json 移植现有代码,请参阅Newtonsoft.Json。

代码示例

本文中的代码示例:

直接使用库,而不是通过框架(如 ASP.NET Core)使用。

将 JsonSerializer 类与自定义类型一起用于序列化以及反序列化。

若要了解如何在不使用 JsonSerializer 的情况下读取和写入 JSON 数据,请参阅如何使用 JSON DOM、如何使用 Utf8JsonReader 和如何使用 Utf8JsonWriter。

使用 WriteIndented 选项设置 JSON 的格式,以方便人类阅读(如果有用)。

对于生产用途,通常会接受此设置的默认值 false,因为添加不必要的空格可能会对性能和带宽使用产生负面影响。

请参考下面的类及其变体:

public class WeatherForecast { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string? Summary { get; set; } } Public Class WeatherForecast Public Property [Date] As DateTimeOffset Public Property TemperatureCelsius As Integer Public Property Summary As String End Class 命名空间

System.Text.Json 命名空间包含所有入口点和主要类型。 System.Text.Json.Serialization 命名空间包含用于高级方案的特性和 API,以及特定于序列化和反序列化的自定义。 本文中演示的代码示例要求将 using 指令用于其中一个或两个命名空间:

using System.Text.Json; using System.Text.Json.Serialization; Imports System.Text.Json Imports System.Text.Json.Serialization

重要

System.Text.Json 不支持 System.Runtime.Serialization 命名空间中的特性。 System.Text.Json 不支持 System.SerializableAttribute 和 ISerializable 接口。 这些类型仅用于二进制和 XML 序列化。 如何将 .NET 对象编写为 JSON(序列化)

若要将 JSON 编写为字符串或文件,请调用 JsonSerializer.Serialize 方法。

下面的示例将 JSON 创建为字符串:

using System.Text.Json; namespace SerializeBasic { public class WeatherForecast { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string? Summary { get; set; } } public class Program { public static void Main() { var weatherForecast = new WeatherForecast { Date = DateTime.Parse("2019-08-01"), TemperatureCelsius = 25, Summary = "Hot" }; string jsonString = JsonSerializer.Serialize(weatherForecast); Console.WriteLine(jsonString); } } } // output: //{"Date":"2019-08-01T00:00:00-07:00","TemperatureCelsius":25,"Summary":"Hot"} Dim jsonString As String

默认情况下,JSON 输出会缩小(将删除空格、缩进和换行符)。

下面的示例使用同步代码创建 JSON 文件:

using System.Text.Json; namespace SerializeToFile { public class WeatherForecast { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string? Summary { get; set; } } public class Program { public static void Main() { var weatherForecast = new WeatherForecast { Date = DateTime.Parse("2019-08-01"), TemperatureCelsius = 25, Summary = "Hot" }; string fileName = "WeatherForecast.json"; string jsonString = JsonSerializer.Serialize(weatherForecast); File.WriteAllText(fileName, jsonString); Console.WriteLine(File.ReadAllText(fileName)); } } } // output: //{"Date":"2019-08-01T00:00:00-07:00","TemperatureCelsius":25,"Summary":"Hot"} jsonString = JsonSerializer.Serialize(weatherForecast1) File.WriteAllText(fileName, jsonString)

下面的示例使用异步代码创建 JSON 文件:

using System.Text.Json; namespace SerializeToFileAsync { public class WeatherForecast { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string? Summary { get; set; } } public class Program { public static async Task Main() { var weatherForecast = new WeatherForecast { Date = DateTime.Parse("2019-08-01"), TemperatureCelsius = 25, Summary = "Hot" }; string fileName = "WeatherForecast.json"; using FileStream createStream = File.Create(fileName); await JsonSerializer.SerializeAsync(createStream, weatherForecast); await createStream.DisposeAsync(); Console.WriteLine(File.ReadAllText(fileName)); } } } // output: //{"Date":"2019-08-01T00:00:00-07:00","TemperatureCelsius":25,"Summary":"Hot"} Dim createStream As FileStream = File.Create(fileName) Await JsonSerializer.SerializeAsync(createStream, weatherForecast1)

前面的示例对要序列化的类型使用类型推理。 Serialize() 的重载采用泛型类型参数:

using System.Text.Json; namespace SerializeWithGenericParameter { public class WeatherForecast { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string? Summary { get; set; } } public class Program { public static void Main() { var weatherForecast = new WeatherForecast { Date = DateTime.Parse("2019-08-01"), TemperatureCelsius = 25, Summary = "Hot" }; string jsonString = JsonSerializer.Serialize(weatherForecast); Console.WriteLine(jsonString); } } } // output: //{"Date":"2019-08-01T00:00:00-07:00","TemperatureCelsius":25,"Summary":"Hot"} jsonString = JsonSerializer.Serialize(Of WeatherForecastWithPOCOs)(weatherForecast) 序列化示例

以下示例演示了如何序列化包含集合属性和用户定义类型的类:

using System.Text.Json; namespace SerializeExtra { public class WeatherForecast { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string? Summary { get; set; } public string? SummaryField; public IList? DatesAvailable { get; set; } public Dictionary? TemperatureRanges { get; set; } public string[]? SummaryWords { get; set; } } public class HighLowTemps { public int High { get; set; } public int Low { get; set; } } public class Program { public static void Main() { var weatherForecast = new WeatherForecast { Date = DateTime.Parse("2019-08-01"), TemperatureCelsius = 25, Summary = "Hot", SummaryField = "Hot", DatesAvailable = new List() { DateTime.Parse("2019-08-01"), DateTime.Parse("2019-08-02") }, TemperatureRanges = new Dictionary { ["Cold"] = new HighLowTemps { High = 20, Low = -10 }, ["Hot"] = new HighLowTemps { High = 60 , Low = 20 } }, SummaryWords = new[] { "Cool", "Windy", "Humid" } }; var options = new JsonSerializerOptions { WriteIndented = true }; string jsonString = JsonSerializer.Serialize(weatherForecast, options); Console.WriteLine(jsonString); } } } // output: //{ // "Date": "2019-08-01T00:00:00-07:00", // "TemperatureCelsius": 25, // "Summary": "Hot", // "DatesAvailable": [ // "2019-08-01T00:00:00-07:00", // "2019-08-02T00:00:00-07:00" // ], // "TemperatureRanges": { // "Cold": { // "High": 20, // "Low": -10 // }, // "Hot": { // "High": 60, // "Low": 20 // } // }, // "SummaryWords": [ // "Cool", // "Windy", // "Humid" // ] //} Public Class WeatherForecastWithPOCOs Public Property [Date] As DateTimeOffset Public Property TemperatureCelsius As Integer Public Property Summary As String Public SummaryField As String Public Property DatesAvailable As IList(Of DateTimeOffset) Public Property TemperatureRanges As Dictionary(Of String, HighLowTemps) Public Property SummaryWords As String() End Class Public Class HighLowTemps Public Property High As Integer Public Property Low As Integer End Class ' serialization output formatted (pretty-printed with whitespace and indentation): ' { ' "Date": "2019-08-01T00:00:00-07:00", ' "TemperatureCelsius": 25, ' "Summary": "Hot", ' "DatesAvailable": [ ' "2019-08-01T00:00:00-07:00", ' "2019-08-02T00:00:00-07:00" ' ], ' "TemperatureRanges": { ' "Cold": { ' "High": 20, ' "Low": -10 ' }, ' "Hot": { ' "High": 60, ' "Low": 20 ' } ' }, ' "SummaryWords": [ ' "Cool", ' "Windy", ' "Humid" ' ] ' } 序列化为 UTF-8

序列化为 UTF-8 字节数组比使用基于字符串的方法大约快 5-10%。 出现这种差别的原因是字节(作为 UTF-8)不需要转换为字符串 (UTF-16)。

若要序列化为 UTF-8 字节数组,请调用 JsonSerializer.SerializeToUtf8Bytes 方法:

byte[] jsonUtf8Bytes =JsonSerializer.SerializeToUtf8Bytes(weatherForecast); Dim jsonUtf8Bytes As Byte() Dim options As JsonSerializerOptions = New JsonSerializerOptions With { .WriteIndented = True } jsonUtf8Bytes = JsonSerializer.SerializeToUtf8Bytes(weatherForecast1, options)

还有一个采用 Utf8JsonWriter 的 Serialize 重载可用。

序列化行为 默认情况下,所有公共属性都会序列化。 可以指定要忽略的属性。 默认编码器会转义非 ASCII 字符、ASCII 范围内的 HTML 敏感字符以及根据 RFC 8259 JSON 规范必须进行转义的字符。 默认情况下,JSON 会缩小。 可以对 JSON 进行优质打印。 默认情况下,JSON 名称的大小写与 .NET 名称匹配。 可以自定义 JSON 名称大小写。 默认情况下,检测到循环引用并引发异常。 可以保留引用并处理循环引用。 默认情况下忽略字段。 可以包含字段。

当你在 ASP.NET Core 应用中间接使用 System.Text.Json 时,某些默认行为会有所不同。 有关详细信息,请参阅 JsonSerializerOptions 的 Web 默认值。

支持的类型包括:

映射到 JavaScript 基元的 .NET 基元,如数值类型、字符串和布尔。 用户定义的普通旧 CLR 对象 (POCO)。 一维和交错数组 (T[][])。 以下命名空间中的集合和字典。 System.Collections System.Collections.Generic System.Collections.Immutable System.Collections.Concurrent System.Collections.Specialized System.Collections.ObjectModel

有关详细信息,请参阅 System.Text.Json 中支持的集合类型。

可以实现自定义转换器以处理其他类型或提供内置转换器不支持的功能。

如何将 JSON 读取为 .NET 对象(反序列化)

反初始化 JSON 的常用方法是首先创建一个类,该类具有属性和表示一个或多个 JSON 属性的字段。 接着,若要从字符串或文件进行反序列化,请调用 JsonSerializer.Deserialize 方法。 对于泛型重载,传递创建的类的类型作为泛型类型参数。 对于非泛型重载,传递创建的类的类型作为方法参数。 可以以同步或异步方式反初始化。

会默认忽略类中未表示的任何 JSON 属性。 此外,如果类型上的任何属性是必需的,但不存在于 JSON 有效负载中,反序列化将失败。

以下示例演示如何对 JSON 字符串进行反初始化:

using System.Text.Json; namespace DeserializeExtra { public class WeatherForecast { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string? Summary { get; set; } public string? SummaryField; public IList? DatesAvailable { get; set; } public Dictionary? TemperatureRanges { get; set; } public string[]? SummaryWords { get; set; } } public class HighLowTemps { public int High { get; set; } public int Low { get; set; } } public class Program { public static void Main() { string jsonString = @"{ ""Date"": ""2019-08-01T00:00:00-07:00"", ""TemperatureCelsius"": 25, ""Summary"": ""Hot"", ""DatesAvailable"": [ ""2019-08-01T00:00:00-07:00"", ""2019-08-02T00:00:00-07:00"" ], ""TemperatureRanges"": { ""Cold"": { ""High"": 20, ""Low"": -10 }, ""Hot"": { ""High"": 60, ""Low"": 20 } }, ""SummaryWords"": [ ""Cool"", ""Windy"", ""Humid"" ] } "; WeatherForecast? weatherForecast = JsonSerializer.Deserialize(jsonString); Console.WriteLine($"Date: {weatherForecast?.Date}"); Console.WriteLine($"TemperatureCelsius: {weatherForecast?.TemperatureCelsius}"); Console.WriteLine($"Summary: {weatherForecast?.Summary}"); } } } // output: //Date: 8/1/2019 12:00:00 AM -07:00 //TemperatureCelsius: 25 //Summary: Hot weatherForecast = JsonSerializer.Deserialize(Of WeatherForecastWithPOCOs)(jsonString)

若要使用同步代码从文件进行反序列化,请将文件读入字符串中,如下面的示例中所示:

using System.Text.Json; namespace DeserializeFromFile { public class WeatherForecast { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string? Summary { get; set; } } public class Program { public static void Main() { string fileName = "WeatherForecast.json"; string jsonString = File.ReadAllText(fileName); WeatherForecast weatherForecast = JsonSerializer.Deserialize(jsonString)!; Console.WriteLine($"Date: {weatherForecast.Date}"); Console.WriteLine($"TemperatureCelsius: {weatherForecast.TemperatureCelsius}"); Console.WriteLine($"Summary: {weatherForecast.Summary}"); } } } // output: //Date: 8/1/2019 12:00:00 AM -07:00 //TemperatureCelsius: 25 //Summary: Hot jsonString = File.ReadAllText(fileName) weatherForecast1 = JsonSerializer.Deserialize(Of WeatherForecast)(jsonString)

若要使用异步代码从文件进行反序列化,请调用 DeserializeAsync 方法:

using System.Text.Json; namespace DeserializeFromFileAsync { public class WeatherForecast { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string? Summary { get; set; } } public class Program { public static async Task Main() { string fileName = "WeatherForecast.json"; using FileStream openStream = File.OpenRead(fileName); WeatherForecast? weatherForecast = await JsonSerializer.DeserializeAsync(openStream); Console.WriteLine($"Date: {weatherForecast?.Date}"); Console.WriteLine($"TemperatureCelsius: {weatherForecast?.TemperatureCelsius}"); Console.WriteLine($"Summary: {weatherForecast?.Summary}"); } } } // output: //Date: 8/1/2019 12:00:00 AM -07:00 //TemperatureCelsius: 25 //Summary: Hot Dim openStream As FileStream = File.OpenRead(fileName) weatherForecast1 = Await JsonSerializer.DeserializeAsync(Of WeatherForecast)(openStream)

提示

如果有要反序列化的 JSON,但没有反序列化的目标类,则除了手动创建所需的类外,还有其他选项:

反序列化为文档对象模型 (JSON DOM),并从 DOM 中提取所需的内容。

DOM 允许你导航到 JSON 有效负载的子节,并反序列化单个值、自定义类型或数组。 有关 JsonNode DOM 的信息,请参阅反序列化 JSON 有效负载的子节。 有关 JsonDocument DOM 的详细信息,请参阅JsonDocument。

直接使用 Utf8JsonReader。

使用 Visual Studio 2022 自动生成所需的类:

复制需要反序列化的 JSON。 创建一个类文件并删除模板代码。 选择“编辑”“选择性粘贴”“将 JSON 粘贴为类”。 结果是可用于反序列化目标的类。 从 UTF-8 进行反序列化

若要从 UTF-8 进行反序列化,请调用采用 ReadOnlySpan 或 Utf8JsonReader 的 JsonSerializer.Deserialize 重载,如下面的示例中所示。 这些示例假设 JSON 处于名为 jsonUtf8Bytes 的字节数组中。

var readOnlySpan = new ReadOnlySpan(jsonUtf8Bytes); WeatherForecast deserializedWeatherForecast = JsonSerializer.Deserialize(readOnlySpan)!; Dim jsonString = Encoding.UTF8.GetString(jsonUtf8Bytes) weatherForecast1 = JsonSerializer.Deserialize(Of WeatherForecast)(jsonString) var utf8Reader = new Utf8JsonReader(jsonUtf8Bytes); WeatherForecast deserializedWeatherForecast = JsonSerializer.Deserialize(ref utf8Reader)!; ' This code example doesn't apply to Visual Basic. For more information, go to the following URL: ' https://learn.microsoft.com/dotnet/standard/serialization/system-text-json-how-to#visual-basic-support 反序列化行为

对 JSON 进行反序列化时,以下行为适用:

默认情况下,属性名称匹配区分大小写。 可以指定不区分大小写。 如果 JSON 包含只读属性的值,则会默认忽略该值。 可将 PreferredObjectCreationHandling 选项设置为 JsonObjectCreationHandling.Populate,以启用对只读属性的反序列化。 序列化程序会忽略非公共构造函数。 支持反序列化为不可变对象或不具有公共 set 访问器的属性。 请参阅不可变类型和记录。 默认情况下,支持将枚举作为数字。 可以将枚举名称序列化为字符串。 默认情况下忽略字段。 可以包含字段。 默认情况下,JSON 中的注释或尾随逗号会引发异常。 可以允许注释和尾随逗号。 默认最大深度为 64。

当你在 ASP.NET Core 应用中间接使用 System.Text.Json 时,某些默认行为会有所不同。 有关详细信息,请参阅 JsonSerializerOptions 的 Web 默认值。

默认情况下,属性名称匹配区分大小写。 可以指定不区分大小写。 如果 JSON 包含只读属性的值,则会忽略该值,并且不引发异常。 序列化程序会忽略非公共构造函数。 支持反序列化为不可变对象或不具有公共 set 访问器的属性。 请参阅不可变类型和记录。 默认情况下,支持将枚举作为数字。 可以将枚举名称序列化为字符串。 默认情况下忽略字段。 可以包含字段。 默认情况下,JSON 中的注释或尾随逗号会引发异常。 可以允许注释和尾随逗号。 默认最大深度为 64。

当你在 ASP.NET Core 应用中间接使用 System.Text.Json 时,某些默认行为会有所不同。 有关详细信息,请参阅 JsonSerializerOptions 的 Web 默认值。

可以实现自定义转换器以提供内置转换器不支持的功能。

序列化为格式化 JSON

若要对 JSON 输出进行优质打印,请将 JsonSerializerOptions.WriteIndented 设置为 true:

using System.Text.Json; namespace SerializeWriteIndented { public class WeatherForecast { public DateTimeOffset Date { get; set; } public int TemperatureCelsius { get; set; } public string? Summary { get; set; } } public class Program { public static void Main() { var weatherForecast = new WeatherForecast { Date = DateTime.Parse("2019-08-01"), TemperatureCelsius = 25, Summary = "Hot" }; var options = new JsonSerializerOptions { WriteIndented = true }; string jsonString = JsonSerializer.Serialize(weatherForecast, options); Console.WriteLine(jsonString); } } } // output: //{ // "Date": "2019-08-01T00:00:00-07:00", // "TemperatureCelsius": 25, // "Summary": "Hot" //} Dim options As JsonSerializerOptions = New JsonSerializerOptions With { .WriteIndented = True } jsonString = JsonSerializer.Serialize(weatherForecast, options)

如果你通过相同的选项重复使用 JsonSerializerOptions,则请勿在每次使用时都创建新的 JsonSerializerOptions 实例。 对每个调用重复使用同一实例。 有关详细信息,请参阅重用 JsonSerializerOptions 实例。

包含字段

在序列化或反序列化时,使用 JsonSerializerOptions.IncludeFields 全局设置或 JsonSerializerOptions.IncludeFields 特性来包含字段,如以下示例中所示:

using System.Text.Json; using System.Text.Json.Serialization; namespace Fields { public class Forecast { public DateTime Date; public int TemperatureC; public string? Summary; } public class Forecast2 { [JsonInclude] public DateTime Date; [JsonInclude] public int TemperatureC; [JsonInclude] public string? Summary; } public class Program { public static void Main() { var json = @"{""Date"":""2020-09-06T11:31:01.923395"",""TemperatureC"":-1,""Summary"":""Cold""} "; Console.WriteLine($"Input JSON: {json}"); var options = new JsonSerializerOptions { IncludeFields = true, }; var forecast = JsonSerializer.Deserialize(json, options)!; Console.WriteLine($"forecast.Date: {forecast.Date}"); Console.WriteLine($"forecast.TemperatureC: {forecast.TemperatureC}"); Console.WriteLine($"forecast.Summary: {forecast.Summary}"); var roundTrippedJson = JsonSerializer.Serialize(forecast, options); Console.WriteLine($"Output JSON: {roundTrippedJson}"); var forecast2 = JsonSerializer.Deserialize(json)!; Console.WriteLine($"forecast2.Date: {forecast2.Date}"); Console.WriteLine($"forecast2.TemperatureC: {forecast2.TemperatureC}"); Console.WriteLine($"forecast2.Summary: {forecast2.Summary}"); roundTrippedJson = JsonSerializer.Serialize(forecast2); Console.WriteLine($"Output JSON: {roundTrippedJson}"); } } } // Produces output like the following example: // //Input JSON: { "Date":"2020-09-06T11:31:01.923395","TemperatureC":-1,"Summary":"Cold"} //forecast.Date: 9/6/2020 11:31:01 AM //forecast.TemperatureC: -1 //forecast.Summary: Cold //Output JSON: { "Date":"2020-09-06T11:31:01.923395","TemperatureC":-1,"Summary":"Cold"} //forecast2.Date: 9/6/2020 11:31:01 AM //forecast2.TemperatureC: -1 //forecast2.Summary: Cold //Output JSON: { "Date":"2020-09-06T11:31:01.923395","TemperatureC":-1,"Summary":"Cold"} Imports System.Text.Json Imports System.Text.Json.Serialization Namespace Fields Public Class Forecast Public [Date] As Date Public TemperatureC As Integer Public Summary As String End Class Public Class Forecast2 Public [Date] As Date Public TemperatureC As Integer Public Summary As String End Class Public NotInheritable Class Program Public Shared Sub Main() Dim json As String = "{""Date"":""2020-09-06T11:31:01.923395"",""TemperatureC"":-1,""Summary"":""Cold""}" Console.WriteLine($"Input JSON: {json}") Dim options As New JsonSerializerOptions With { .IncludeFields = True } Dim forecast1 As Forecast = JsonSerializer.Deserialize(Of Forecast)(json, options) Console.WriteLine($"forecast.Date: {forecast1.[Date]}") Console.WriteLine($"forecast.TemperatureC: {forecast1.TemperatureC}") Console.WriteLine($"forecast.Summary: {forecast1.Summary}") Dim roundTrippedJson As String = JsonSerializer.Serialize(forecast1, options) Console.WriteLine($"Output JSON: {roundTrippedJson}") Dim forecast21 As Forecast2 = JsonSerializer.Deserialize(Of Forecast2)(json) Console.WriteLine($"forecast2.Date: {forecast21.[Date]}") Console.WriteLine($"forecast2.TemperatureC: {forecast21.TemperatureC}") Console.WriteLine($"forecast2.Summary: {forecast21.Summary}") roundTrippedJson = JsonSerializer.Serialize(forecast21) Console.WriteLine($"Output JSON: {roundTrippedJson}") End Sub End Class End Namespace ' Produces output like the following example: ' 'Input JSON: { "Date":"2020-09-06T11:31:01.923395","TemperatureC":-1,"Summary":"Cold"} 'forecast.Date: 9/6/2020 11:31:01 AM 'forecast.TemperatureC: -1 'forecast.Summary: Cold 'Output JSON: { "Date":"2020-09-06T11:31:01.923395","TemperatureC":-1,"Summary":"Cold"} 'forecast2.Date: 9/6/2020 11:31:01 AM 'forecast2.TemperatureC: -1 'forecast2.Summary: Cold 'Output JSON: { "Date":"2020-09-06T11:31:01.923395","TemperatureC":-1,"Summary":"Cold"}

若要忽略只读字段,请使用 JsonSerializerOptions.IgnoreReadOnlyFields 全局设置。

HttpClient 和 HttpContent 扩展方法

序列化和反序列化来自网络的 JSON 有效负载是常见的操作。 HttpClient 和 HttpContent 上的扩展方法允许在单个代码行中执行这些操作。 这些扩展方法使用 JsonSerializerOptions 的 Web 默认值。

以下示例说明了 HttpClientJsonExtensions.GetFromJsonAsync 和 HttpClientJsonExtensions.PostAsJsonAsync 的用法:

using System.Net.Http.Json; namespace HttpClientExtensionMethods { public class User { public int Id { get; set; } public string? Name { get; set; } public string? Username { get; set; } public string? Email { get; set; } } public class Program { public static async Task Main() { using HttpClient client = new() { BaseAddress = new Uri("https://jsonplaceholder.typicode.com") }; // Get the user information. User? user = await client.GetFromJsonAsync("users/1"); Console.WriteLine($"Id: {user?.Id}"); Console.WriteLine($"Name: {user?.Name}"); Console.WriteLine($"Username: {user?.Username}"); Console.WriteLine($"Email: {user?.Email}"); // Post a new user. HttpResponseMessage response = await client.PostAsJsonAsync("users", user); Console.WriteLine( $"{(response.IsSuccessStatusCode ? "Success" : "Error")} - {response.StatusCode}"); } } } // Produces output like the following example but with different names: // //Id: 1 //Name: Tyler King //Username: Tyler //Email: Tyler @contoso.com //Success - Created Imports System.Net.Http Imports System.Net.Http.Json Namespace HttpClientExtensionMethods Public Class User Public Property Id As Integer Public Property Name As String Public Property Username As String Public Property Email As String End Class Public Class Program Public Shared Async Function Main() As Task Using client As New HttpClient With { .BaseAddress = New Uri("https://jsonplaceholder.typicode.com") } ' Get the user information. Dim user1 As User = Await client.GetFromJsonAsync(Of User)("users/1") Console.WriteLine($"Id: {user1.Id}") Console.WriteLine($"Name: {user1.Name}") Console.WriteLine($"Username: {user1.Username}") Console.WriteLine($"Email: {user1.Email}") ' Post a new user. Dim response As HttpResponseMessage = Await client.PostAsJsonAsync("users", user1) Console.WriteLine( $"{(If(response.IsSuccessStatusCode, "Success", "Error"))} - {response.StatusCode}") End Using End Function End Class End Namespace ' Produces output like the following example but with different names: ' 'Id: 1 'Name: Tyler King 'Username: Tyler 'Email: Tyler @contoso.com 'Success - Created

此外还有 System.Text.Json 上的 System.Text.Json 的扩展方法。

请参阅 System.Text.Json 概述


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有