Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
Expand Up @@ -3,7 +3,7 @@

namespace SystemTextJsonSamples
{
public class RoundtripDictionaryTkeyEnumTValue
public class ConvertDictionaryTkeyEnumTValue
{
public static void Run()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

namespace SystemTextJsonSamples
{
public class DeserializeInferredTypesToObject
public class ConvertInferredTypesToObject
{
public static void Run()
{
Expand Down
4 changes: 2 additions & 2 deletions snippets/core/system-text-json/csharp/ConvertPolymorphic.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

namespace SystemTextJsonSamples
{
class SerializePolymorphic
public class ConvertPolymorphic
{
public static void Run()
{
Expand Down Expand Up @@ -45,4 +45,4 @@ public static void Run()
Console.WriteLine($"JSON output:\n{jsonString}\n");
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ public override DateTimeOffset Read(

public override void Write(
Utf8JsonWriter writer,
DateTimeOffset value,
DateTimeOffset dateTimeValue,
JsonSerializerOptions options) =>
writer.WriteStringValue(value.ToString(
writer.WriteStringValue(dateTimeValue.ToString(
"MM/dd/yyyy", CultureInfo.InvariantCulture));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ public override DateTimeOffset Read(

public override void Write(
Utf8JsonWriter writer,
DateTimeOffset value,
DateTimeOffset dateTimeValue,
JsonSerializerOptions options)
{
writer.WriteStringValue(value);
writer.WriteStringValue(dateTimeValue);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,11 @@ public static void Run()
string jsonString;

// Serialize to create input JSON
var weatherForecast = WeatherForecastFactories.CreateWeatherForecast();
WeatherForecast weatherForecast = WeatherForecastFactories.CreateWeatherForecast();
var serializeOptions = new JsonSerializerOptions
{
WriteIndented = true
};
serializeOptions.WriteIndented = true;
jsonString = JsonSerializer.Serialize(weatherForecast, serializeOptions);
Console.WriteLine($"JSON input:\n{jsonString}\n");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,36 +12,31 @@ 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);
var options = new JsonSerializerOptions();
options.WriteIndented = true;
options.Converters.Add(new DateTimeOffsetNullHandlingConverter());
jsonString = JsonSerializer.Serialize(wf, options);
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 = JsonSerializer.Deserialize<WeatherForecast>(jsonString, options);
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.
// The null-date JSON deserializes with error if the converter isn't used.
try
{
wf = JsonSerializer.Deserialize<WeatherForecast>(jsonString);
}
catch (Exception ex)
catch (JsonException 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 = JsonSerializer.Deserialize<WeatherForecast>(jsonString, options);
wf.DisplayPropertyValues();
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,13 @@ 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);
var options = new JsonSerializerOptions();
options.WriteIndented = true;
options.Converters.Add(new WeatherForecastRequiredPropertyConverter());
jsonString = JsonSerializer.Serialize(wf, options);
Console.WriteLine($"JSON with Date:\n{jsonString}\n");

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

jsonString = @"{""TemperatureCelsius"": 25,""Summary"":""Hot""}";
Expand All @@ -34,17 +32,14 @@ public static void Run()
Console.WriteLine("Deserialize with converter");
try
{
deserializeOptions = new JsonSerializerOptions();
deserializeOptions.Converters.Add(new WeatherForecastRequiredPropertyConverter());
wf = JsonSerializer.Deserialize<WeatherForecast>(jsonString, deserializeOptions);
wf = JsonSerializer.Deserialize<WeatherForecast>(jsonString, options);
}
catch (Exception ex)
catch (JsonException ex)
{
Console.WriteLine($"Exception thrown: {ex.Message}\n");
}
// wf object is unchanged if exception is thrown.
wf.DisplayPropertyValues();
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,13 @@ public override Dictionary<TKey, TValue> Read(
throw new JsonException();
}

Dictionary<TKey, TValue> value = new Dictionary<TKey, TValue>();
Dictionary<TKey, TValue> dictionary = new Dictionary<TKey, TValue>();

while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndObject)
{
return value;
return dictionary;
}

// Get the key.
Expand Down Expand Up @@ -107,20 +107,20 @@ public override Dictionary<TKey, TValue> Read(
}

// Add to dictionary.
value.Add(key, v);
dictionary.Add(key, v);
}

throw new JsonException();
}

public override void Write(
Utf8JsonWriter writer,
Dictionary<TKey, TValue> value,
Dictionary<TKey, TValue> dictionary,
JsonSerializerOptions options)
{
writer.WriteStartObject();

foreach (KeyValuePair<TKey, TValue> kvp in value)
foreach (KeyValuePair<TKey, TValue> kvp in dictionary)
{
writer.WritePropertyName(kvp.Key.ToString());

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

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

public int X { get { return _x; } }
public int Y { get { return _y; } }
public int X { get; }
public int Y { get; }
}
// </SnippetImmutablePoint>
}
70 changes: 39 additions & 31 deletions snippets/core/system-text-json/csharp/ImmutablePointConverter.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,28 @@
using System;
using System.Diagnostics;
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";
private readonly JsonEncodedText XName = JsonEncodedText.Encode("X");
private readonly JsonEncodedText YName = JsonEncodedText.Encode("Y");

private readonly JsonConverter<int> _intConverter;

public ImmutablePointConverter(JsonSerializerOptions options)
{
if (options?.GetConverter(typeof(int)) is JsonConverter<int> intConverter)
{
_intConverter = intConverter;
}
else
{
throw new InvalidOperationException();
}
}

public override ImmutablePoint Read(
ref Utf8JsonReader reader,
Expand All @@ -33,13 +47,12 @@ public override ImmutablePoint Read(
throw new JsonException();
}

string propertyName = reader.GetString();
if (propertyName == XName)
if (reader.ValueTextEquals(XName.EncodedUtf8Bytes))
{
x = ReadProperty(ref reader, options);
xSet = true;
}
else if (propertyName == YName)
else if (reader.ValueTextEquals(YName.EncodedUtf8Bytes))
{
y = ReadProperty(ref reader, options);
ySet = true;
Expand All @@ -56,23 +69,15 @@ public override ImmutablePoint Read(
throw new JsonException();
}

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

if (!xSet || !ySet)
else
{
throw new JsonException();
}
Expand All @@ -87,26 +92,29 @@ public override ImmutablePoint Read(
return new ImmutablePoint(x, y);
}

public int ReadProperty(ref Utf8JsonReader reader, JsonSerializerOptions options)
private 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();
}
Debug.Assert(reader.TokenType == JsonTokenType.PropertyName);

reader.Read();
return _intConverter.Read(ref reader, typeof(int), options);
}

private void WriteProperty(Utf8JsonWriter writer, JsonEncodedText name, int intValue, JsonSerializerOptions options)
{
writer.WritePropertyName(name);
_intConverter.Write(writer, intValue, options);
}

public override void Write(
Utf8JsonWriter writer,
ImmutablePoint value,
ImmutablePoint point,
JsonSerializerOptions options)
{
// Don't pass in options when recursively calling Serialize.
JsonSerializer.Serialize(writer, value);
writer.WriteStartObject();
WriteProperty(writer, XName, point.X, options);
WriteProperty(writer, YName, point.Y, options);
writer.WriteEndObject();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

namespace SystemTextJsonSamples
{
class JsonDocumentDataAccess
public class JsonDocumentDataAccess
{
public static void Run()
{
Expand Down Expand Up @@ -73,6 +73,5 @@ private static void AverageGrades_Alternative(string jsonString)
// </SnippetAverageGrades2>

}

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

namespace SystemTextJsonSamples
{
class JsonDocumentWriteJson
public class JsonDocumentWriteJson
{
public static void Run()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ public override long Read(ref Utf8JsonReader reader, Type type, JsonSerializerOp
return reader.GetInt64();
}

public override void Write(Utf8JsonWriter writer, long value, JsonSerializerOptions options)
public override void Write(Utf8JsonWriter writer, long longValue, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString());
writer.WriteStringValue(longValue.ToString());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public override object Read(

public override void Write(
Utf8JsonWriter writer,
object value,
object objectToWrite,
JsonSerializerOptions options) =>
throw new InvalidOperationException("Should not get here.");
}
Expand Down
Loading