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
25 changes: 25 additions & 0 deletions snippets/core/system-text-json/csharp/IForecast.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System;

namespace SystemTextJsonSamples
{
public interface IForecast
{
public DateTimeOffset Date { get; set; }
public int TemperatureCelsius { get; set; }
public string Summary { get; set; }
}

public class Forecast : IForecast
{
public DateTimeOffset Date { get; set; }
public int TemperatureCelsius { get; set; }
public string Summary { get; set; }
public int WindSpeed { get; set; }
}

public class Forecasts
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice!

{
public IForecast Monday { get; set; }
public object Tuesday { get; set; }
}
}
5 changes: 5 additions & 0 deletions snippets/core/system-text-json/csharp/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace SystemTextJsonSamples
Expand Down Expand Up @@ -106,6 +108,9 @@ static async Task Main(string[] args)
Console.WriteLine("\n============================= Utf8Reader from file\n");
Utf8ReaderFromFile.Run();

string jsonString = File.ReadAllText("Universities.json");
ValueTextEqualsExample.Run(Encoding.UTF8.GetBytes(jsonString));

Console.WriteLine("\n============================= Utf8Reader from byte array\n");
Utf8ReaderFromBytes.Run();

Expand Down
57 changes: 51 additions & 6 deletions snippets/core/system-text-json/csharp/SerializePolymorphic.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,35 +14,80 @@ public static void Run()

Console.WriteLine("Base class generic type - derived class properties omitted");
// <SnippetSerializeDefault>
var serializeOptions = new JsonSerializerOptions
var options = new JsonSerializerOptions
{
WriteIndented = true
};
jsonString = JsonSerializer.Serialize<WeatherForecast>(weatherForecast, serializeOptions);
jsonString = JsonSerializer.Serialize<WeatherForecast>(weatherForecast, options);
// </SnippetSerializeDefault>

Console.WriteLine($"JSON output:\n{jsonString}\n");

Console.WriteLine("Object generic type parameter - derived class properties included");
// <SnippetSerializeObject>
serializeOptions = new JsonSerializerOptions
options = new JsonSerializerOptions
{
WriteIndented = true
};
jsonString = JsonSerializer.Serialize<object>(weatherForecast, serializeOptions);
jsonString = JsonSerializer.Serialize<object>(weatherForecast, options);
// </SnippetSerializeObject>
Console.WriteLine($"JSON output:\n{jsonString}\n");


Console.WriteLine("GetType() type parameter - derived class properties included");
// <SnippetSerializeGetType>
serializeOptions = new JsonSerializerOptions
options = new JsonSerializerOptions
{
WriteIndented = true
};
jsonString = JsonSerializer.Serialize(weatherForecast, weatherForecast.GetType(), serializeOptions);
jsonString = JsonSerializer.Serialize(weatherForecast, weatherForecast.GetType(), options);
// </SnippetSerializeGetType>
Console.WriteLine($"JSON output:\n{jsonString}\n");

Console.WriteLine("Extra properties on interface implementations included only for object properties");
// <SnippetSerializeInterface>
var forecasts = new Forecasts
{
Monday = new Forecast
{
Date = DateTime.Parse("2020-01-06"),
TemperatureCelsius = 10,
Summary = "Cool",
WindSpeed = 8
},
Tuesday = new Forecast
{
Date = DateTime.Parse("2020-01-07"),
TemperatureCelsius = 11,
Summary = "Rainy",
WindSpeed = 10
}
};

options = new JsonSerializerOptions
{
WriteIndented = true
};
jsonString = JsonSerializer.Serialize(forecasts, options);
// </SnippetSerializeInterface>
Console.WriteLine($"{jsonString}\n");

WeatherForecastWithPrevious weatherForecastWithPrevious = WeatherForecastFactories.CreateWeatherForecastWithPrevious();
WeatherForecastWithPreviousAsObject weatherForecastWithPreviousAsObject = WeatherForecastFactories.CreateWeatherForecastWithPreviousAsObject();

Console.WriteLine("Second level derived class properties included only for object properties");
// <SnippetSerializeSecondLevel>
options = new JsonSerializerOptions
{
WriteIndented = true
};
jsonString = JsonSerializer.Serialize(weatherForecastWithPreviousAsObject, options);
// </SnippetSerializeSecondLevel>
Console.WriteLine($"JSON output with WindSpeed:\n{jsonString}\n");
jsonString = JsonSerializer.Serialize(
weatherForecastWithPrevious,
options);
Console.WriteLine($"JSON output without WindSpeed:\n{jsonString}\n");
}
}
}
34 changes: 21 additions & 13 deletions snippets/core/system-text-json/csharp/Utf8ReaderFromFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,37 +8,45 @@ namespace SystemTextJsonSamples
public class Utf8ReaderFromFile
{
private static readonly byte[] s_nameUtf8 = Encoding.UTF8.GetBytes("name");
private static ReadOnlySpan<byte> Utf8Bom => new byte[] { 0xEF, 0xBB, 0xBF };
public static void Run()
{
// Read as UTF-16 and transcode to UTF-8 to convert to a Span<byte>
string fileName = "Universities.json";
string jsonString = File.ReadAllText(fileName);
ReadOnlySpan<byte> jsonReadOnlySpan = Encoding.UTF8.GetBytes(jsonString);
// ReadAllBytes if the file encoding is UTF-8:
string fileName = "UniversitiesUtf8.json";
ReadOnlySpan<byte> jsonReadOnlySpan = File.ReadAllBytes(fileName);

// Read past the UTF-8 BOM bytes if a BOM exists.
if (jsonReadOnlySpan.StartsWith(Utf8Bom))
{
jsonReadOnlySpan = jsonReadOnlySpan.Slice(Utf8Bom.Length);
}

// Or read as UTF-16 and transcode to UTF-8 to convert to a ReadOnlySpan<byte>
//string fileName = "Universities.json";
//string jsonString = File.ReadAllText(fileName);
//ReadOnlySpan<byte> jsonReadOnlySpan = Encoding.UTF8.GetBytes(jsonString);

// Or ReadAllBytes if the file encoding is UTF-8:
//string fileName = "UniversitiesUtf8.json";
//ReadOnlySpan<byte> jsonReadOnlySpan = File.ReadAllBytes(fileName);

int count = 0;
int total = 0;

var json = new Utf8JsonReader(jsonReadOnlySpan, isFinalBlock: true, state: default);
var reader = new Utf8JsonReader(jsonReadOnlySpan);

while (json.Read())
while (reader.Read())
{
JsonTokenType tokenType = json.TokenType;
JsonTokenType tokenType = reader.TokenType;

switch (tokenType)
{
case JsonTokenType.StartObject:
total++;
break;
case JsonTokenType.PropertyName:
if (json.ValueTextEquals(s_nameUtf8))
if (reader.ValueTextEquals(s_nameUtf8))
{
// Assume valid JSON, known schema
json.Read();
if (json.GetString().EndsWith("University"))
reader.Read();
if (reader.GetString().EndsWith("University"))
{
count++;
}
Expand Down
41 changes: 41 additions & 0 deletions snippets/core/system-text-json/csharp/ValueTextEqualsExample.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System;
using System.IO;
using System.Text;
using System.Text.Json;

namespace SystemTextJsonSamples
{
public class ValueTextEqualsExample
{
// <SnippetDefineUtf8Var>
private static readonly byte[] s_nameUtf8 = Encoding.UTF8.GetBytes("name");
// </SnippetDefineUtf8Var>
public static void Run(ReadOnlySpan<byte> jsonReadOnlySpan)
{
int count = 0;
int total = 0;
var reader = new Utf8JsonReader(jsonReadOnlySpan);

// <SnippetUseUtf8Var>
while (reader.Read())
{
JsonTokenType tokenType = reader.TokenType;

switch (tokenType)
{
case JsonTokenType.StartObject:
total++;
break;
case JsonTokenType.PropertyName:
if (reader.ValueTextEquals(s_nameUtf8))
{
count++;
}
break;
}
// </SnippetUseUtf8Var>
}
Console.WriteLine($"{count} out of {total} have \"name\" properties");
}
}
}
44 changes: 44 additions & 0 deletions snippets/core/system-text-json/csharp/WeatherForecast.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,26 @@ public class WeatherForecast
}
// </SnippetWF>

// <SnippetWFWithPrevious>
public class WeatherForecastWithPrevious
{
public DateTimeOffset Date { get; set; }
public int TemperatureCelsius { get; set; }
public string Summary { get; set; }
public WeatherForecast PreviousForecast { get; set; }
}
// </SnippetWFWithPrevious>

// <SnippetWFWithPreviousAsObject>
public class WeatherForecastWithPreviousAsObject
{
public DateTimeOffset Date { get; set; }
public int TemperatureCelsius { get; set; }
public string Summary { get; set; }
public object PreviousForecast { get; set; }
}
// </SnippetWFWithPreviousAsObject>

// <SnippetWFWithLong>
public class WeatherForecastWithLong
{
Expand Down Expand Up @@ -306,6 +326,30 @@ public static WeatherForecast CreateWeatherForecast()
return weatherForecast;
}

public static WeatherForecastWithPrevious CreateWeatherForecastWithPrevious()
{
var weatherForecast = new WeatherForecastWithPrevious
{
Date = DateTime.Parse("2019-08-01"),
TemperatureCelsius = 25,
Summary = "Hot",
PreviousForecast = CreateWeatherForecastDerived()
};
return weatherForecast;
}

public static WeatherForecastWithPreviousAsObject CreateWeatherForecastWithPreviousAsObject()
{
var weatherForecast = new WeatherForecastWithPreviousAsObject
{
Date = DateTime.Parse("2019-08-01"),
TemperatureCelsius = 25,
Summary = "Hot",
PreviousForecast = CreateWeatherForecastDerived()
};
return weatherForecast;
}

public static WeatherForecastWithLong CreateWeatherForecastWithLong()
{
var weatherForecast = new WeatherForecastWithLong
Expand Down