How to serialize and deserialize (marshal and unmarshal) JSON in .NET
This article shows how to use the System.Text.Json namespace to serialize to and deserialize from JavaScript Object Notation (JSON). If you're porting existing code from Newtonsoft.Json
, see How to migrate to System.Text.Json
.
Code samples
The code samples in this article:
Use the library directly, not through a framework such as ASP.NET Core.
Use the JsonSerializer class with custom types to serialize from and deserialize into.
For information about how to read and write JSON data without using
JsonSerializer
, see How to use the JSON DOM, How to use Utf8JsonReader, and How to use Utf8JsonWriter.Use the WriteIndented option to format the JSON for human readability when that is helpful.
For production use, you would typically accept the default value of
false
for this setting, since adding unnecessary whitespace may incur a negative impact on performance and bandwidth usage.Refer to the following class and variants of it:
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
Namespaces
The System.Text.Json namespace contains all the entry points and the main types. The System.Text.Json.Serialization namespace contains attributes and APIs for advanced scenarios and customization specific to serialization and deserialization. The code examples shown in this article require using
directives for one or both of these namespaces:
using System.Text.Json;
using System.Text.Json.Serialization;
Imports System.Text.Json
Imports System.Text.Json.Serialization
Important
- Attributes from the System.Runtime.Serialization namespace aren't supported by
System.Text.Json
. - System.SerializableAttribute and the ISerializable interface aren't supported by
System.Text.Json
. These types are used only for Binary and XML serialization.
How to write .NET objects as JSON (serialize)
To write JSON to a string or to a file, call the JsonSerializer.Serialize method.
The following example creates JSON as a string:
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
The JSON output is minified (whitespace, indentation, and new-line characters are removed) by default.
The following example uses synchronous code to create a JSON file:
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)
The following example uses asynchronous code to create a JSON file:
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)
The preceding examples use type inference for the type being serialized. An overload of Serialize()
takes a generic type parameter:
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>(weatherForecast);
Console.WriteLine(jsonString);
}
}
}
// output:
//{"Date":"2019-08-01T00:00:00-07:00","TemperatureCelsius":25,"Summary":"Hot"}
jsonString = JsonSerializer.Serialize(Of WeatherForecastWithPOCOs)(weatherForecast)
Serialization example
Here's an example showing how a class that contains collection properties and a user-defined type is serialized:
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<DateTimeOffset>? DatesAvailable { get; set; }
public Dictionary<string, HighLowTemps>? 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<DateTimeOffset>()
{ DateTime.Parse("2019-08-01"), DateTime.Parse("2019-08-02") },
TemperatureRanges = new Dictionary<string, HighLowTemps>
{
["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"
' ]
' }
Serialize to UTF-8
Serializing to a UTF-8 byte array is about 5-10% faster than using the string-based methods. The difference is because the bytes (as UTF-8) don't need to be converted to strings (UTF-16).
To serialize to a UTF-8 byte array, call the JsonSerializer.SerializeToUtf8Bytes method:
byte[] jsonUtf8Bytes =JsonSerializer.SerializeToUtf8Bytes(weatherForecast);
Dim jsonUtf8Bytes As Byte()
Dim options As JsonSerializerOptions = New JsonSerializerOptions With {
.WriteIndented = True
}
jsonUtf8Bytes = JsonSerializer.SerializeToUtf8Bytes(weatherForecast1, options)
A Serialize overload that takes a Utf8JsonWriter is also available.
Serialization behavior
- By default, all public properties are serialized. You can specify properties to ignore.
- The default encoder escapes non-ASCII characters, HTML-sensitive characters within the ASCII-range, and characters that must be escaped according to the RFC 8259 JSON spec.
- By default, JSON is minified. You can pretty-print the JSON.
- By default, casing of JSON names matches the .NET names. You can customize JSON name casing.
- By default, circular references are detected and exceptions thrown. You can preserve references and handle circular references.
- By default, fields are ignored. You can include fields.
When you use System.Text.Json indirectly in an ASP.NET Core app, some default behaviors are different. For more information, see Web defaults for JsonSerializerOptions.
Supported types include:
- .NET primitives that map to JavaScript primitives, such as numeric types, strings, and Boolean.
- User-defined plain old CLR objects (POCOs).
- One-dimensional and jagged arrays (
T[][]
). - Collections and dictionaries from the following namespaces.
For more information, see Supported collection types in System.Text.Json.
You can implement custom converters to handle additional types or to provide functionality that isn't supported by the built-in converters.
How to read JSON as .NET objects (deserialize)
A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer.Deserialize method. For the generic overloads, you pass the type of the class you created as the generic type parameter. For the non-generic overloads, you pass the type of the class you created as a method parameter. You can deserialize either synchronously or asynchronously.
Any JSON properties that aren't represented in your class are ignored by default. Also, if any properties on the type are required but not present in the JSON payload, deserialization will fail.
The following example shows how to deserialize a JSON string:
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<DateTimeOffset>? DatesAvailable { get; set; }
public Dictionary<string, HighLowTemps>? 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<WeatherForecast>(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)
To deserialize from a file by using synchronous code, read the file into a string, as shown in the following example:
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<WeatherForecast>(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)
To deserialize from a file by using asynchronous code, call the DeserializeAsync method:
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<WeatherForecast>(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)
Tip
If you have JSON that you want to deserialize, and you don't have the class to deserialize it into, you have options other than manually creating the class that you need:
Deserialize into a JSON DOM (document object model) and extract what you need from the DOM.
The DOM lets you navigate to a subsection of a JSON payload and deserialize a single value, a custom type, or an array. For information about the JsonNode DOM, see Deserialize subsections of a JSON payload. For information about the JsonDocument DOM, see How to search a JsonDocument and JsonElement for sub-elements.
Use the Utf8JsonReader directly.
Use Visual Studio 2022 to automatically generate the class you need:
- Copy the JSON that you need to deserialize.
- Create a class file and delete the template code.
- Choose Edit > Paste Special > Paste JSON as Classes. The result is a class that you can use for your deserialization target.
Deserialize from UTF-8
To deserialize from UTF-8, call a JsonSerializer.Deserialize overload that takes a ReadOnlySpan<byte>
or a Utf8JsonReader
, as shown in the following examples. The examples assume the JSON is in a byte array named jsonUtf8Bytes.
var readOnlySpan = new ReadOnlySpan<byte>(jsonUtf8Bytes);
WeatherForecast deserializedWeatherForecast =
JsonSerializer.Deserialize<WeatherForecast>(readOnlySpan)!;
Dim jsonString = Encoding.UTF8.GetString(jsonUtf8Bytes)
weatherForecast1 = JsonSerializer.Deserialize(Of WeatherForecast)(jsonString)
var utf8Reader = new Utf8JsonReader(jsonUtf8Bytes);
WeatherForecast deserializedWeatherForecast =
JsonSerializer.Deserialize<WeatherForecast>(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
Deserialization behavior
The following behaviors apply when deserializing JSON:
- By default, property name matching is case-sensitive. You can specify case-insensitivity.
- If the JSON contains a value for a read-only property, the value is ignored by default. You can set the PreferredObjectCreationHandling option to JsonObjectCreationHandling.Populate to enable deserialization to read-only properties.
- Non-public constructors are ignored by the serializer.
- Deserialization to immutable objects or properties that don't have public
set
accessors is supported. See Immutable types and records. - By default, enums are supported as numbers. You can serialize enum names as strings.
- By default, fields are ignored. You can include fields.
- By default, comments or trailing commas in the JSON throw exceptions. You can allow comments and trailing commas.
- The default maximum depth is 64.
When you use System.Text.Json indirectly in an ASP.NET Core app, some default behaviors are different. For more information, see Web defaults for JsonSerializerOptions.
- By default, property name matching is case-sensitive. You can specify case-insensitivity.
- If the JSON contains a value for a read-only property, the value is ignored and no exception is thrown.
- Non-public constructors are ignored by the serializer.
- Deserialization to immutable objects or properties that don't have public
set
accessors is supported. See Immutable types and records. - By default, enums are supported as numbers. You can serialize enum names as strings.
- By default, fields are ignored. You can include fields.
- By default, comments or trailing commas in the JSON throw exceptions. You can allow comments and trailing commas.
- The default maximum depth is 64.
When you use System.Text.Json indirectly in an ASP.NET Core app, some default behaviors are different. For more information, see Web defaults for JsonSerializerOptions.
You can implement custom converters to provide functionality that isn't supported by the built-in converters.
Serialize to formatted JSON
To pretty-print the JSON output, set JsonSerializerOptions.WriteIndented to 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)
If you use JsonSerializerOptions
repeatedly with the same options, don't create a new JsonSerializerOptions
instance each time you use it. Reuse the same instance for every call. For more information, see Reuse JsonSerializerOptions instances.
Include fields
Use the JsonSerializerOptions.IncludeFields global setting or the [JsonInclude] attribute to include fields when serializing or deserializing, as shown in the following example:
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<Forecast>(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>(forecast, options);
Console.WriteLine($"Output JSON: {roundTrippedJson}");
var forecast2 = JsonSerializer.Deserialize<Forecast2>(json)!;
Console.WriteLine($"forecast2.Date: {forecast2.Date}");
Console.WriteLine($"forecast2.TemperatureC: {forecast2.TemperatureC}");
Console.WriteLine($"forecast2.Summary: {forecast2.Summary}");
roundTrippedJson = JsonSerializer.Serialize<Forecast2>(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
<JsonInclude>
Public [Date] As Date
<JsonInclude>
Public TemperatureC As Integer
<JsonInclude>
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"}
To ignore read-only fields, use the JsonSerializerOptions.IgnoreReadOnlyFields global setting.
HttpClient and HttpContent extension methods
Serializing and deserializing JSON payloads from the network are common operations. Extension methods on HttpClient and HttpContent let you do these operations in a single line of code. These extension methods use web defaults for JsonSerializerOptions.
The following example illustrates use of HttpClientJsonExtensions.GetFromJsonAsync and 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<User>("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
There are also extension methods for System.Text.Json on HttpContent.
See also
Feedback
Submit and view feedback for