Skip to content
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

5.0 updates to System.Text.Json docs #21108

Merged
merged 52 commits into from
Nov 5, 2020
Merged
Show file tree
Hide file tree
Changes from 35 commits
Commits
Show all changes
52 commits
Select commit Hold shift + click to select a range
9e1468e
zp trial
tdykstra Oct 14, 2020
7566c05
don't split up table
tdykstra Oct 14, 2020
3512304
fix zp name
tdykstra Oct 14, 2020
1bd06c3
draft
tdykstra Oct 16, 2020
047df57
draft
tdykstra Oct 16, 2020
8eeb1d8
add description metadata
tdykstra Oct 16, 2020
8f618bc
preserve references
tdykstra Oct 19, 2020
e6161e6
preserve references
tdykstra Oct 19, 2020
bb80293
temp delete file causing compile error
tdykstra Oct 19, 2020
877bedf
fix employee name
tdykstra Oct 19, 2020
3e491ca
quoted numbers
tdykstra Oct 19, 2020
2edc219
fix snippet links
tdykstra Oct 19, 2020
5d04709
fix snippet link
tdykstra Oct 19, 2020
ac72629
quoted numbers
tdykstra Oct 19, 2020
76fc04d
quoted numbers
tdykstra Oct 19, 2020
9249ef7
number handling default
tdykstra Oct 20, 2020
56ee6e4
referenceresolver
tdykstra Oct 20, 2020
a5321db
options creation
tdykstra Oct 21, 2020
e80d7ad
fix ref resolver
tdykstra Oct 21, 2020
f112016
options tweaks
tdykstra Oct 21, 2020
740ed4f
address feedback
tdykstra Oct 21, 2020
56e5346
immutable types
tdykstra Oct 21, 2020
73ec526
fields
tdykstra Oct 21, 2020
61628ac
move sample output blocks to code files
tdykstra Oct 21, 2020
d0c1546
fix link
tdykstra Oct 22, 2020
ecd50b0
ignore value type defaults
tdykstra Oct 22, 2020
2a905b2
jsonignoreattribute
tdykstra Oct 22, 2020
50d8a02
non-string key dict
tdykstra Oct 22, 2020
34aeae1
nonpublic accessors
tdykstra Oct 23, 2020
a9bf725
converter handle null
tdykstra Oct 23, 2020
4834f33
proofread
tdykstra Oct 23, 2020
b80d041
add highlighting
tdykstra Oct 26, 2020
173f882
fix build errors
tdykstra Oct 26, 2020
8e9bc65
corrections
tdykstra Oct 26, 2020
aa65767
acrolinx
tdykstra Oct 26, 2020
da2fd64
shorten code lines
tdykstra Oct 26, 2020
e7db9f9
restore some shortened lines
tdykstra Oct 26, 2020
2629f5b
address feedback
tdykstra Oct 26, 2020
b89d504
address feedback
tdykstra Oct 30, 2020
526cfe0
fix link and address feedback
tdykstra Oct 30, 2020
b284229
address feedback
tdykstra Nov 5, 2020
2260214
Merge branch 'master' into stj5a
tdykstra Nov 5, 2020
42d5e29
fix links
tdykstra Nov 5, 2020
568c3e9
fix merge conflict
tdykstra Nov 5, 2020
a92e7c5
fix merge conflict
tdykstra Nov 5, 2020
78c30d5
tweak headings
tdykstra Nov 5, 2020
9868e56
make text style of s.t.j consistent
tdykstra Nov 5, 2020
e358dc9
acrolinx
tdykstra Nov 5, 2020
7ec0df1
markdownlint
tdykstra Nov 5, 2020
58a1690
try view=net-5.0 on xref link
tdykstra Nov 5, 2020
9c7de46
fix links
tdykstra Nov 5, 2020
870d637
misc proofread fixes
tdykstra Nov 5, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System;
using System.Text.Json;

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()
{
WriteIndented = true
};

JsonSerializerOptions optionsCopy = new(options);
string forecastJson = JsonSerializer.Serialize<Forecast>(forecast, optionsCopy);
Console.WriteLine($"Output JSON:\n{forecastJson}");
}
}
}

// Produces output like the following example:
//
//Output JSON:
//{
// "Date": "2020-10-21T15:40:06.8998502-07:00",
// "TemperatureC": 40,
// "Summary": "Hot"
//}
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;

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; }
tdykstra marked this conversation as resolved.
Show resolved Hide resolved

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}");
}
}
}

// Produces output like the following example:
//
//Output JSON:
//{
// "x": 1,
tdykstra marked this conversation as resolved.
Show resolved Hide resolved
// "y": 2,
// "description": null,
// "additionalValues": {
// "3": 4,
// "5": 6
// }
//}
//X: 1
//Y: 2
//Additional values count: 2
//AdditionalValues[3]: 4
//AdditionalValues[5]: 6
//Description: No description provided.
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System;
using System.Text.Json;

namespace Fields
{
public class Forecast
{
public DateTime Date;
public int TemperatureC;
public string Summary;
}
tdykstra marked this conversation as resolved.
Show resolved Hide resolved
public class Program
{
public static void Main()
{
var json = "{\"date\":\"2020-09-06T11:31:01.923395-07:00\",\"temperatureC\":-1,\"summary\":\"Cold\"} ";
Console.WriteLine($"Input JSON: {json}");

var options = new JsonSerializerOptions(JsonSerializerDefaults.Web)
tdykstra marked this conversation as resolved.
Show resolved Hide resolved
{
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}");
}
}
}

// Produces output like the following example:
//
//Input JSON: { "date":"2020-09-06T11:31:01.923395-07:00","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-07:00","temperatureC":-1,"summary":"Cold"}
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
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)}");
}
}
}

// Produces output like the following example:
//
//Output JSON[
// {
// "$id": "79301726-9d94-499a-8cdc-0c8bcc4c9b63",
// "Name": "Tyler",
// "Spouse": {
// "$id": "94833059-35f2-4fdd-96ee-94fd0484969a",
// "Name": "Adrian",
// "Spouse": {
// "$ref": "79301726-9d94-499a-8cdc-0c8bcc4c9b63"
// }
// }
// },
// {
// "$ref": "94833059-35f2-4fdd-96ee-94fd0484969a"
// }
//]
//Adrian is Tyler's spouse: True
//Tyler is Adrian's spouse: True
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System;
using System.Net.Http;
using System.Net.Http.Json;
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}");
}
}
}

// Produces output like the following example but with different names:
//
//Id: 1
//Name: Tyler King
//Username: Tyler
//Email: Tyler @contoso.com
//Success - Created
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#nullable enable
using System;
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);
}
}
}

// Produces output like the following example:
//
//{ "Date":"2020-10-21T15:40:06.8920138-07:00"}
Loading