Skip to content

Commit

Permalink
Samples for Newtonsoft migration doc (#1837)
Browse files Browse the repository at this point in the history
  • Loading branch information
tdykstra authored Dec 12, 2019
1 parent 251c415 commit 4adbf4c
Show file tree
Hide file tree
Showing 19 changed files with 636 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace SystemTextJsonSamples
{
public class DateTimeOffsetNullHandlingConverter : JsonConverter<DateTimeOffset>

{
public override DateTimeOffset Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Null)
{
return default;
}
return reader.GetDateTimeOffset();
}

public override void Write(
Utf8JsonWriter writer,
DateTimeOffset value,
JsonSerializerOptions options)
{
writer.WriteStringValue(value);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

namespace SystemTextJsonSamples
{
public class ConvertInferredTypesToObject
public class DeserializeInferredTypesToObject
{
public static void Run()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace SystemTextJsonSamples
{
public class DeserializeNullToNonnullableType
{
public static void Run()
{
string jsonString;
var wf = WeatherForecastFactories.CreateWeatherForecast();

var serializeOptions = new JsonSerializerOptions();
serializeOptions.WriteIndented = true;
serializeOptions.Converters.Add(new DateTimeOffsetNullHandlingConverter());
jsonString = JsonSerializer.Serialize(wf, serializeOptions);
Console.WriteLine($"JSON with valid Date:\n{jsonString}\n");

var deserializeOptions = new JsonSerializerOptions();
deserializeOptions.Converters.Add(new DateTimeOffsetNullHandlingConverter());
wf = JsonSerializer.Deserialize<WeatherForecast>(jsonString, deserializeOptions);
wf.DisplayPropertyValues();

jsonString = @"{""Date"": null,""TemperatureCelsius"": 25,""Summary"":""Hot""}";
Console.WriteLine($"JSON with null Date:\n{jsonString}\n");

// The missing-date JSON deserializes with error if the converter isn't used.
try
{
wf = JsonSerializer.Deserialize<WeatherForecast>(jsonString);
}
catch (Exception ex)
{
Console.WriteLine($"Exception thrown: {ex.Message}\n");
}

Console.WriteLine("Deserialize with converter");
deserializeOptions = new JsonSerializerOptions();
deserializeOptions.Converters.Add(new DateTimeOffsetNullHandlingConverter());
wf = JsonSerializer.Deserialize<WeatherForecast>(jsonString, deserializeOptions);
wf.DisplayPropertyValues();
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace SystemTextJsonSamples
{
public class DeserializeRequiredProperty
{
public static void Run()
{
string jsonString;
var wf = WeatherForecastFactories.CreateWeatherForecast();

var serializeOptions = new JsonSerializerOptions();
serializeOptions.WriteIndented = true;
serializeOptions.Converters.Add(new WeatherForecastRequiredPropertyConverter());
jsonString = JsonSerializer.Serialize(wf, serializeOptions);
Console.WriteLine($"JSON with Date:\n{jsonString}\n");

var deserializeOptions = new JsonSerializerOptions();
deserializeOptions.Converters.Add(new WeatherForecastRequiredPropertyConverter());
wf = JsonSerializer.Deserialize<WeatherForecast>(jsonString, deserializeOptions);
wf.DisplayPropertyValues();

jsonString = @"{""TemperatureCelsius"": 25,""Summary"":""Hot""}";
Console.WriteLine($"JSON without Date:\n{jsonString}\n");

// The missing-date JSON deserializes without error if the converter isn't used.
Console.WriteLine("Deserialize without converter");
wf = JsonSerializer.Deserialize<WeatherForecast>(jsonString);
wf.DisplayPropertyValues();

Console.WriteLine("Deserialize with converter");
try
{
deserializeOptions = new JsonSerializerOptions();
deserializeOptions.Converters.Add(new WeatherForecastRequiredPropertyConverter());
wf = JsonSerializer.Deserialize<WeatherForecast>(jsonString, deserializeOptions);
}
catch (Exception ex)
{
Console.WriteLine($"Exception thrown: {ex.Message}\n");
}
// wf object is unchanged if exception is thrown.
wf.DisplayPropertyValues();
}
}

}
19 changes: 19 additions & 0 deletions snippets/core/system-text-json/csharp/ImmutablePoint.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
namespace SystemTextJsonSamples
{
// <SnippetImmutablePoint>
public struct ImmutablePoint
{
private readonly int _x;
private readonly int _y;

public ImmutablePoint(int x, int y)
{
_x = x;
_y = y;
}

public int X { get { return _x; } }
public int Y { get { return _y; } }
}
// </SnippetImmutablePoint>
}
112 changes: 112 additions & 0 deletions snippets/core/system-text-json/csharp/ImmutablePointConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
using System;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace SystemTextJsonSamples
{
public class ImmutablePointConverter : JsonConverter<ImmutablePoint>

{
private const string XName = "X";
private const string YName = "Y";

public override ImmutablePoint Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartObject)
{
throw new JsonException();
};

int x = default;
bool xSet = false;

int y = default;
bool ySet = false;

// Get the first property.
reader.Read();
if (reader.TokenType != JsonTokenType.PropertyName)
{
throw new JsonException();
}

string propertyName = reader.GetString();
if (propertyName == XName)
{
x = ReadProperty(ref reader, options);
xSet = true;
}
else if (propertyName == YName)
{
y = ReadProperty(ref reader, options);
ySet = true;
}
else
{
throw new JsonException();
}

// Get the second property.
reader.Read();
if (reader.TokenType != JsonTokenType.PropertyName)
{
throw new JsonException();
}

propertyName = reader.GetString();
if (propertyName == XName)
{
x = ReadProperty(ref reader, options);
xSet = true;
}
else if (propertyName == YName)
{
y = ReadProperty(ref reader, options);
ySet = true;
}
else
{
throw new JsonException();
}

if (!xSet || !ySet)
{
throw new JsonException();
}

reader.Read();

if (reader.TokenType != JsonTokenType.EndObject)
{
throw new JsonException();
}

return new ImmutablePoint(x, y);
}

public int ReadProperty(ref Utf8JsonReader reader, JsonSerializerOptions options)
{
if (options?.GetConverter(typeof(int)) is JsonConverter<int> intConverter)
{
reader.Read();
return intConverter.Read(ref reader, typeof(int), options);
}
else
{
throw new JsonException();
}
}

public override void Write(
Utf8JsonWriter writer,
ImmutablePoint value,
JsonSerializerOptions options)
{
// Don't pass in options when recursively calling Serialize.
JsonSerializer.Serialize(writer, value);
}
}
}
31 changes: 31 additions & 0 deletions snippets/core/system-text-json/csharp/LongToStringConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System;
using System.Buffers;
using System.Buffers.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace SystemTextJsonSamples
{
public class LongToStringConverter : JsonConverter<long>
{
public override long Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.String)
{
ReadOnlySpan<byte> span = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan;
if (Utf8Parser.TryParse(span, out long number, out int bytesConsumed) && span.Length == bytesConsumed)
return number;

if (Int64.TryParse(reader.GetString(), out number))
return number;
}

return reader.GetInt64();
}

public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString());
}
}
}
24 changes: 21 additions & 3 deletions snippets/core/system-text-json/csharp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,31 @@ static async Task Main(string[] args)
RegisterConverterWithAttributeOnType.Run();

Console.WriteLine("\n============================= Custom converter Dictionary with TKey = Enum\n");
ConvertDictionaryTkeyEnumTValue.Run();
RoundtripDictionaryTkeyEnumTValue.Run();

Console.WriteLine("\n============================= Custom converter Polymorphic\n");
ConvertPolymorphic.Run();
RoundtripPolymorphic.Run();

Console.WriteLine("\n============================= Custom converter inferred types to Object\n");
ConvertInferredTypesToObject.Run();
DeserializeInferredTypesToObject.Run();

Console.WriteLine("\n============================= Custom converter long to string\n");
RoundtripLongToString.Run();

Console.WriteLine("\n============================= Callbacks\n");
RoundtripCallbacks.Run();

Console.WriteLine("\n============================= Required property\n");
DeserializeRequiredProperty.Run();

Console.WriteLine("\n============================= Null value to nonnullable type\n");
DeserializeNullToNonnullableType.Run();

Console.WriteLine("\n============================= Immutable struct\n");
RoundtripImmutableStruct.Run();

Console.WriteLine("\n============================= Runtime property exclusion\n");
SerializeRuntimePropertyExclusion.Run();

Console.WriteLine("\n============================= JsonDocument data access\n");
JsonDocumentDataAccess.Run();
Expand Down
36 changes: 36 additions & 0 deletions snippets/core/system-text-json/csharp/RoundtripCallbacks.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace SystemTextJsonSamples
{
public class RoundtripCallbacks
{
public static void Run()
{
string jsonString;
var wf = WeatherForecastFactories.CreateWeatherForecast();
wf.DisplayPropertyValues();

// <SnippetSerialize>
var serializeOptions = new JsonSerializerOptions();
serializeOptions.Converters.Add(new WeatherForecastCallbacksConverter());
serializeOptions.WriteIndented = true;
jsonString = JsonSerializer.Serialize(wf, serializeOptions);
// </SnippetSerialize>

Console.WriteLine($"JSON output:\n{jsonString}\n");
//jsonString = @"{""Date"": null,""TemperatureCelsius"": 25,""Summary"":""Hot""}";

// <SnippetDeserialize>
var deserializeOptions = new JsonSerializerOptions();
deserializeOptions.Converters.Add(new WeatherForecastCallbacksConverter());
wf = JsonSerializer.Deserialize<WeatherForecast>(jsonString, deserializeOptions);
// <SnippetDeserialize>

wf.DisplayPropertyValues();
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

namespace SystemTextJsonSamples
{
public class ConvertDictionaryTkeyEnumTValue
public class RoundtripDictionaryTkeyEnumTValue
{
public static void Run()
{
Expand Down
Loading

0 comments on commit 4adbf4c

Please sign in to comment.