Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Warning
This component has been archived and is not available in the current version of the Windows Community Toolkit.
While there are no immediate plans to port this component to 8.x, the community is welcome to express interest or contribute to its inclusion.
For more information:
Original documentation follows below.
You should implement IObjectSerializer when you need to write data using this toolkit's helpers with a custom serializer. If you don't, a default JSON serializer will be used otherwise.
Methods
| Methods | Return Type | Description |
|---|---|---|
| Serialize<T>(T) | object | Serialize an object of type T into a object. |
| Deserialize<T>(object) | T | Deserialize a object to an object of type T. |
Examples
System.Text.Json
using Microsoft.Toolkit.Uwp.Helpers;
using System.Text.Json;
namespace Contoso.Helpers
{
public class SystemTextJsonObjectSerializer : IObjectSerializer
{
public object Serialize<T>(T value) => JsonSerializer.Serialize(value);
public T Deserialize<T>(object value) => JsonSerializer.Deserialize<T>((string)value);
}
}
Json.NET
using Microsoft.Toolkit.Uwp.Helpers;
using Newtonsoft.Json;
namespace Contoso.Helpers
{
public class JsonNetObjectSerializer : IObjectSerializer
{
// Specify your serialization settings
private readonly JsonSerializerSettings settings = new JsonSerializerSettings();
public object Serialize<T>(T value) => JsonConvert.SerializeObject(value, typeof(T), Formatting.Indented , settings);
public T Deserialize<T>(object value) => JsonConvert.DeserializeObject<T>((string)value, settings);
}
}
DataContract
using Microsoft.Toolkit.Uwp.Helpers;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
namespace Contoso.Helpers
{
public class DataContractObjectSerializer : IObjectSerializer
{
// Specify your serialization settings
private readonly DataContractSerializerSettings settings = new DataContractSerializerSettings();
public object Serialize<T>(T value)
{
var serializer = new DataContractSerializer(typeof(T), settings);
using (var stringWriter = new StringWriter())
using (var xmlWriter = XmlWriter.Create(stringWriter))
{
serializer.WriteObject(xmlWriter, value);
return stringWriter.ToString();
}
}
public T Deserialize<T>(object value)
{
var serializer = new DataContractSerializer(typeof(T), settings);
using (var stringReader = new StringReader((string)value))
using (var xmlReader = XmlReader.Create(stringReader))
{
return (T)serializer.ReadObject(xmlReader);
}
}
}
}
Requirements
| Device family | Universal, 10.0.16299.0 or higher |
|---|---|
| Namespace | Microsoft.Toolkit.Uwp |
| NuGet package | Microsoft.Toolkit.Uwp |
API
Related topics
.NET Community Toolkit