Serialization Examples
Installation
System.Text.Json Package
dotnet add package UUID.Serialization.System
Install the System.Text.Json serialization package via NuGet.
Newtonsoft.Json Package
dotnet add package UUID.Serialization.Newtonsoft
Install the Newtonsoft.Json serialization package via NuGet.
System.Text.Json Examples
Basic Serialization
using System.Text.Json;
// Configure JsonSerializerOptions
var options = new JsonSerializerOptions();
options.Converters.Add(new UUIDConverter());
// Create a UUID
var uuid = UUID.New();
// Serialize
string json = JsonSerializer.Serialize(uuid, options);
// Deserialize
UUID deserialized = JsonSerializer.Deserialize(json, options);
Basic example of UUID serialization and deserialization using System.Text.Json.
Collection Serialization
// Create an array of UUIDs
UUID[] uuids = new[] { UUID.New(), UUID.New(), UUID.New() };
// Serialize array
string jsonArray = JsonSerializer.Serialize(uuids, options);
// Deserialize array
UUID[] deserializedArray = JsonSerializer.Deserialize(jsonArray, options);
Example of serializing and deserializing arrays of UUIDs using System.Text.Json.
Model Serialization
public class User
{
public UUID Id { get; set; }
public string Name { get; set; }
}
var user = new User
{
Id = UUID.New(),
Name = "John Doe"
};
// Serialize model
string json = JsonSerializer.Serialize(user, options);
// Deserialize model
User deserializedUser = JsonSerializer.Deserialize(json, options);
Example of using UUIDs in model classes with System.Text.Json serialization.
Newtonsoft.Json Examples
Basic Serialization
using Newtonsoft.Json;
// Configure JsonSerializerSettings
var settings = new JsonSerializerSettings();
settings.Converters.Add(new UUIDConverter());
// Create a UUID
var uuid = UUID.New();
// Serialize
string json = JsonConvert.SerializeObject(uuid, settings);
// Deserialize
UUID deserialized = JsonConvert.DeserializeObject(json, settings);
Basic example of UUID serialization and deserialization using Newtonsoft.Json.
Collection Serialization
// Create an array of UUIDs
UUID[] uuids = new[] { UUID.New(), UUID.New(), UUID.New() };
// Serialize array
string jsonArray = JsonConvert.SerializeObject(uuids, settings);
// Deserialize array
UUID[] deserializedArray = JsonConvert.DeserializeObject(jsonArray, settings);
Example of serializing and deserializing arrays of UUIDs using Newtonsoft.Json.
Model Serialization
public class User
{
public UUID Id { get; set; }
public string Name { get; set; }
}
var user = new User
{
Id = UUID.New(),
Name = "John Doe"
};
// Serialize model
string json = JsonConvert.SerializeObject(user, settings);
// Deserialize model
User deserializedUser = JsonConvert.DeserializeObject(json, settings);
Example of using UUIDs in model classes with Newtonsoft.Json serialization.
Advanced Examples
Custom Model with UUID List
public class Team
{
public string Name { get; set; }
public List MemberIds { get; set; }
}
var team = new Team
{
Name = "Development Team",
MemberIds = new List
{
UUID.New(),
UUID.New()
}
};
// System.Text.Json
string json = JsonSerializer.Serialize(team, options);
Team deserializedTeam = JsonSerializer.Deserialize(json, options);
// Newtonsoft.Json
string json = JsonConvert.SerializeObject(team, settings);
Team deserializedTeam = JsonConvert.DeserializeObject(json, settings);
Example of serializing a model containing a list of UUIDs.
Dictionary with UUID Keys
// Create a dictionary with UUID keys
Dictionary userNames = new()
{
{ UUID.New(), "John Doe" },
{ UUID.New(), "Jane Smith" }
};
// System.Text.Json
string json = JsonSerializer.Serialize(userNames, options);
Dictionary deserializedDict = JsonSerializer.Deserialize>(json, options);
// Newtonsoft.Json
string json = JsonConvert.SerializeObject(userNames, settings);
Dictionary deserializedDict = JsonConvert.DeserializeObject>(json, settings);
Example of using UUIDs as dictionary keys in serialization.
Custom JSON Property Name
public class UserProfile
{
[JsonPropertyName("user_id")] // System.Text.Json
[JsonProperty("user_id")] // Newtonsoft.Json
public UUID Id { get; set; }
[JsonPropertyName("display_name")] // System.Text.Json
[JsonProperty("display_name")] // Newtonsoft.Json
public string Name { get; set; }
}
var profile = new UserProfile
{
Id = UUID.New(),
Name = "John Doe"
};
// The serialized JSON will use the custom property names:
// {
// "user_id": "...",
// "display_name": "John Doe"
// }
Example of customizing JSON property names when serializing UUIDs.
Nullable UUID Properties
public class Document
{
public UUID Id { get; set; }
public UUID? ParentId { get; set; } // Nullable UUID
public string Title { get; set; }
}
var document = new Document
{
Id = UUID.New(),
ParentId = null, // This will be serialized as null
Title = "My Document"
};
// System.Text.Json
string json = JsonSerializer.Serialize(document, options);
Document deserializedDoc = JsonSerializer.Deserialize(json, options);
// Newtonsoft.Json
string json = JsonConvert.SerializeObject(document, settings);
Document deserializedDoc = JsonConvert.DeserializeObject(json, settings);
Example of working with nullable UUID properties in models.
Best Practices
Global Serializer Configuration
// System.Text.Json in ASP.NET Core
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new UUIDConverter());
});
}
// Newtonsoft.Json in ASP.NET Core
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.Converters.Add(new UUIDConverter());
});
Example of configuring UUID serialization globally in an ASP.NET Core application.
Custom Serialization Format
public class CustomUUIDConverter : JsonConverter
{
public override UUID Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
string value = reader.GetString();
return value != null ? UUID.Parse($"prefix_{value}") : default;
}
public override void Write(Utf8JsonWriter writer, UUID value, JsonSerializerOptions options)
{
writer.WriteStringValue($"prefix_{value}");
}
}
Example of implementing a custom UUID converter with a specific format.
Error Handling Examples
System.Text.Json Error Handling
try
{
// Invalid JSON string
string invalidJson = "\"invalid-uuid-format\"";
// This will throw an exception
UUID uuid = JsonSerializer.Deserialize(invalidJson, options);
}
catch (JsonException ex)
{
Console.WriteLine($"Failed to deserialize UUID: {ex.Message}");
}
Example of handling invalid UUID deserialization with System.Text.Json.
Newtonsoft.Json Error Handling
try
{
// Invalid JSON string
string invalidJson = "\"invalid-uuid-format\"";
// This will throw an exception
UUID uuid = JsonConvert.DeserializeObject(invalidJson, settings);
}
catch (JsonReaderException ex)
{
Console.WriteLine($"Failed to deserialize UUID: {ex.Message}");
}
Example of handling invalid UUID deserialization with Newtonsoft.Json.