-
Notifications
You must be signed in to change notification settings - Fork 6k
5.0 updates to System.Text.Json docs #21108
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 20 commits
Commits
Show all changes
52 commits
Select commit
Hold shift + click to select a range
9e1468e
zp trial
tdykstra 7566c05
don't split up table
tdykstra 3512304
fix zp name
tdykstra 1bd06c3
draft
tdykstra 047df57
draft
tdykstra 8eeb1d8
add description metadata
tdykstra 8f618bc
preserve references
tdykstra e6161e6
preserve references
tdykstra bb80293
temp delete file causing compile error
tdykstra 877bedf
fix employee name
tdykstra 3e491ca
quoted numbers
tdykstra 2edc219
fix snippet links
tdykstra 5d04709
fix snippet link
tdykstra ac72629
quoted numbers
tdykstra 76fc04d
quoted numbers
tdykstra 9249ef7
number handling default
tdykstra 56ee6e4
referenceresolver
tdykstra a5321db
options creation
tdykstra e80d7ad
fix ref resolver
tdykstra f112016
options tweaks
tdykstra 740ed4f
address feedback
tdykstra 56e5346
immutable types
tdykstra 73ec526
fields
tdykstra 61628ac
move sample output blocks to code files
tdykstra d0c1546
fix link
tdykstra ecd50b0
ignore value type defaults
tdykstra 2a905b2
jsonignoreattribute
tdykstra 50d8a02
non-string key dict
tdykstra 34aeae1
nonpublic accessors
tdykstra a9bf725
converter handle null
tdykstra 4834f33
proofread
tdykstra b80d041
add highlighting
tdykstra 173f882
fix build errors
tdykstra 8e9bc65
corrections
tdykstra aa65767
acrolinx
tdykstra da2fd64
shorten code lines
tdykstra e7db9f9
restore some shortened lines
tdykstra 2629f5b
address feedback
tdykstra b89d504
address feedback
tdykstra 526cfe0
fix link and address feedback
tdykstra b284229
address feedback
tdykstra 2260214
Merge branch 'master' into stj5a
tdykstra 42d5e29
fix links
tdykstra 568c3e9
fix merge conflict
tdykstra a92e7c5
fix merge conflict
tdykstra 78c30d5
tweak headings
tdykstra 9868e56
make text style of s.t.j consistent
tdykstra e358dc9
acrolinx
tdykstra 7ec0df1
markdownlint
tdykstra 58a1690
try view=net-5.0 on xref link
tdykstra 9c7de46
fix links
tdykstra 870d637
misc proofread fixes
tdykstra File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
37 changes: 37 additions & 0 deletions
37
docs/standard/serialization/snippets/system-text-json-how-to-5-0/csharp/CopyOptions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
| ||
using System; | ||
using System.Collections.Generic; | ||
using System.Text.Json; | ||
using System.Text.Json.Serialization; | ||
|
||
namespace CopyOptions | ||
{ | ||
public class Forecast | ||
{ | ||
public DateTime Date { get; init; } | ||
public int TemperatureC { get; set; } | ||
public string Summary { get; set; } | ||
}; | ||
|
||
public class Program | ||
{ | ||
public static void Main() | ||
{ | ||
Forecast forecast = new() | ||
{ | ||
Date = DateTime.Now, | ||
TemperatureC = 40, | ||
Summary = "Hot" | ||
}; | ||
|
||
JsonSerializerOptions options = new(); | ||
JsonSerializerOptions optionsCopy = new(options) | ||
{ | ||
WriteIndented = true | ||
}; | ||
|
||
string forecastJson = JsonSerializer.Serialize<Forecast>(forecast, optionsCopy); | ||
Console.WriteLine($"Output JSON:\n{forecastJson}"); | ||
} | ||
} | ||
} |
75 changes: 75 additions & 0 deletions
75
...rd/serialization/snippets/system-text-json-how-to-5-0/csharp/CustomConverterHandleNull.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Text.Json; | ||
using System.Text.Json.Serialization; | ||
using System.Diagnostics.CodeAnalysis; | ||
|
||
namespace CustomConverterHandleNull | ||
{ | ||
public class Point | ||
{ | ||
public int X { get; } | ||
public int Y { get; } | ||
|
||
public Dictionary<int, int> AdditionalValues; | ||
|
||
[JsonConverter(typeof(DescriptionConverter))] | ||
public string Description { get; set; } | ||
|
||
public Point() | ||
{ | ||
} | ||
|
||
// Specify which ctor should be used when deserializing. | ||
// Attribute not needed if this is the only ctor. | ||
[JsonConstructor] | ||
public Point(int x, int y) => (X, Y) = (x, y); | ||
} | ||
|
||
public class DescriptionConverter : JsonConverter<string> | ||
{ | ||
public override bool HandleNull => true; | ||
|
||
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | ||
{ | ||
string val = reader.GetString(); | ||
return val ?? "No description provided."; | ||
} | ||
|
||
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) | ||
{ | ||
writer.WriteStringValue(value); | ||
} | ||
} | ||
tdykstra marked this conversation as resolved.
Show resolved
Hide resolved
|
||
public class Program | ||
{ | ||
private static JsonSerializerOptions options = new JsonSerializerOptions(JsonSerializerDefaults.Web) | ||
{ | ||
IncludeFields = true, | ||
tdykstra marked this conversation as resolved.
Show resolved
Hide resolved
|
||
WriteIndented = true | ||
}; | ||
|
||
public static void Main() | ||
{ | ||
var point = new Point(1, 2) | ||
{ | ||
AdditionalValues = new Dictionary<int, int> | ||
{ | ||
[3] = 4, | ||
[5] = 6, | ||
} | ||
}; | ||
|
||
string serialized = JsonSerializer.Serialize(point, options); | ||
Console.WriteLine($"Output JSON:\n{serialized}"); | ||
|
||
point = JsonSerializer.Deserialize<Point>(serialized, options); | ||
Console.WriteLine($"X: {point.X}"); | ||
Console.WriteLine($"Y: {point.Y}"); | ||
Console.WriteLine($"Additional values count: {point.AdditionalValues.Count}"); | ||
Console.WriteLine($"AdditionalValues[3]: {point.AdditionalValues[3]}"); | ||
Console.WriteLine($"AdditionalValues[5]: {point.AdditionalValues[5]}"); | ||
Console.WriteLine($"Description: {point.Description}"); | ||
} | ||
} | ||
} |
41 changes: 41 additions & 0 deletions
41
docs/standard/serialization/snippets/system-text-json-how-to-5-0/csharp/Fields.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Text.Json; | ||
using System.Text.Json.Serialization; | ||
|
||
namespace Fields | ||
{ | ||
public class Forecast | ||
{ | ||
public DateTime Date; | ||
public int TemperatureC; | ||
public int TemperatureF; | ||
public string Summary; | ||
} | ||
public class Program | ||
{ | ||
public static void Main() | ||
{ | ||
var json = "{\"date\":\"2020-09-06T11:31:01.923395-07:00\",\"temperatureC\":-1,\"temperatureF\":31,\"summary\":\"Scorching\"} "; | ||
Console.WriteLine($"Input JSON: {json}"); | ||
|
||
var options = new JsonSerializerOptions() | ||
{ | ||
PropertyNameCaseInsensitive = true, | ||
IncludeFields = true, | ||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase | ||
}; | ||
var forecast = JsonSerializer.Deserialize<Forecast>(json, options); | ||
|
||
Console.WriteLine($"forecast.Date: {forecast.Date}"); | ||
Console.WriteLine($"forecast.TemperatureC: {forecast.TemperatureC}"); | ||
Console.WriteLine($"forecast.TemperatureF: {forecast.TemperatureF}"); | ||
Console.WriteLine($"forecast.Summary: {forecast.Summary}"); | ||
|
||
var roundTrippedJson = JsonSerializer.Serialize<Forecast>(forecast, options); | ||
|
||
Console.WriteLine($"Output JSON: {roundTrippedJson}"); | ||
|
||
} | ||
} | ||
} |
78 changes: 78 additions & 0 deletions
78
...serialization/snippets/system-text-json-how-to-5-0/csharp/GuidReferenceResolverExample.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Collections.Immutable; | ||
using System.Diagnostics; | ||
using System.Text.Json; | ||
using System.Text.Json.Serialization; | ||
|
||
namespace GuidReferenceResolverExample | ||
{ | ||
public class Person | ||
{ | ||
internal Guid Id { get; set; } | ||
public string Name { get; set; } | ||
public Person Spouse { get; set; } | ||
} | ||
|
||
public class GuidReferenceResolver : ReferenceResolver | ||
{ | ||
private readonly IDictionary<Guid, Person> _people = new Dictionary<Guid, Person>(); | ||
|
||
public override object ResolveReference(string referenceId) | ||
{ | ||
Guid id = new Guid(referenceId); | ||
|
||
Person p; | ||
_people.TryGetValue(id, out p); | ||
tdykstra marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
return p; | ||
} | ||
|
||
public override string GetReference(object value, out bool alreadyExists) | ||
{ | ||
Person p = (Person)value; | ||
|
||
alreadyExists = _people.ContainsKey(p.Id); | ||
_people[p.Id] = p; | ||
tdykstra marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
return p.Id.ToString(); | ||
} | ||
|
||
public override void AddReference(string reference, object value) | ||
{ | ||
Guid id = new Guid(reference); | ||
Person person = (Person)value; | ||
person.Id = id; | ||
_people[id] = person; | ||
} | ||
} | ||
|
||
static class Program | ||
{ | ||
public static void Main() | ||
{ | ||
Person tyler = new() { Id = Guid.NewGuid(), Name = "Tyler" }; | ||
Person adrian = new() { Id = Guid.NewGuid(), Name = "Adrian" }; | ||
tyler.Spouse = adrian; | ||
adrian.Spouse = tyler; | ||
var people = ImmutableArray.Create(tyler, adrian); | ||
|
||
var options = new JsonSerializerOptions | ||
{ | ||
WriteIndented = true, | ||
ReferenceHandler = new ReferenceHandler<GuidReferenceResolver>() | ||
}; | ||
|
||
string json = JsonSerializer.Serialize(people, options); | ||
Console.WriteLine($"Output JSON {json}"); | ||
|
||
List<Person> peopleDeserialized = JsonSerializer.Deserialize<List<Person>>(json, options); | ||
|
||
Person tylerDeserialized = people[0]; | ||
Person adrianDeserialized = people[1]; | ||
|
||
Console.WriteLine($"Adrian is Tyler's spouse: {tylerDeserialized.Equals(adrianDeserialized.Spouse)}"); | ||
Console.WriteLine($"Tyler is Adrian's spouse: {adrianDeserialized.Equals(tylerDeserialized.Spouse)}"); | ||
} | ||
} | ||
} |
37 changes: 37 additions & 0 deletions
37
...d/serialization/snippets/system-text-json-how-to-5-0/csharp/HttpClientExtensionMethods.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Net.Http; | ||
using System.Net.Http.Json; | ||
using System.Text.Json; | ||
using System.Text.Json.Serialization; | ||
using System.Threading.Tasks; | ||
|
||
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() | ||
{ | ||
var client = new HttpClient(); | ||
client.BaseAddress = new Uri("https://jsonplaceholder.typicode.com"); | ||
tdykstra marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
// 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}"); | ||
} | ||
} | ||
} |
37 changes: 37 additions & 0 deletions
37
...erialization/snippets/system-text-json-how-to-5-0/csharp/IgnoreValueDefaultOnSerialize.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
#nullable enable | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Text.Json; | ||
using System.Text.Json.Serialization; | ||
|
||
namespace IgnoreValueDefaultOnSerialize | ||
{ | ||
public class Forecast | ||
{ | ||
public DateTime Date { get; set; } | ||
public int TemperatureC { get; set; } | ||
public string? Summary { get; set; } | ||
}; | ||
|
||
public class Program | ||
{ | ||
public static void Main() | ||
{ | ||
|
||
Forecast forecast = new() | ||
{ | ||
Date = DateTime.Now, | ||
Summary = null, | ||
TemperatureC = default(int) | ||
}; | ||
|
||
JsonSerializerOptions options = new() | ||
{ | ||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault | ||
}; | ||
|
||
string forecastJson = JsonSerializer.Serialize<Forecast>(forecast, options); | ||
Console.WriteLine(forecastJson); | ||
} | ||
} | ||
} |
49 changes: 49 additions & 0 deletions
49
docs/standard/serialization/snippets/system-text-json-how-to-5-0/csharp/ImmutableTypes.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Text.Json; | ||
using System.Text.Json.Serialization; | ||
|
||
namespace ImmutableTypes | ||
{ | ||
public struct Forecast | ||
{ | ||
public DateTime Date { get; } | ||
public int TemperatureC { get; } | ||
public int TemperatureF { get; } | ||
public string Summary { get; } | ||
tdykstra marked this conversation as resolved.
Show resolved
Hide resolved
|
||
[JsonConstructor] | ||
public Forecast( | ||
DateTime date, | ||
int temperatureC, | ||
int temperatureF, | ||
string summary) => | ||
(Date, TemperatureC, TemperatureF, Summary) = | ||
(date, temperatureC, temperatureF, summary); | ||
} | ||
public class Program | ||
{ | ||
public static void Main() | ||
{ | ||
var json = "{\"date\":\"2020-09-06T11:31:01.923395-07:00\",\"temperatureC\":-1,\"temperatureF\":31,\"summary\":\"Scorching\"} "; | ||
Console.WriteLine($"Input JSON: {json}"); | ||
|
||
var options = new JsonSerializerOptions() | ||
{ | ||
PropertyNameCaseInsensitive = true, | ||
//IncludeFields = true, | ||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase | ||
}; | ||
var forecast = JsonSerializer.Deserialize<Forecast>(json, options); | ||
|
||
Console.WriteLine($"forecast.Date: {forecast.Date}"); | ||
Console.WriteLine($"forecast.TemperatureC: {forecast.TemperatureC}"); | ||
Console.WriteLine($"forecast.TemperatureF: {forecast.TemperatureF}"); | ||
Console.WriteLine($"forecast.Summary: {forecast.Summary}"); | ||
|
||
var roundTrippedJson = JsonSerializer.Serialize<Forecast>(forecast, options); | ||
|
||
Console.WriteLine($"Output JSON: {roundTrippedJson}"); | ||
|
||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.