// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace CommunityToolkit.Common.Helpers; /// /// A bare-bones serializer which knows how to deal with primitive types and strings only. /// It is recommended for more complex scenarios to implement your own based on System.Text.Json, Newtonsoft.Json, or DataContractJsonSerializer see https://aka.ms/wct/storagehelper-migration /// public class SystemSerializer : IObjectSerializer { /// /// Take a primitive value from storage and return it as the requested type using the API. /// /// Type to convert value to. /// Value from storage to convert. /// Deserialized value or default value. public T Deserialize(string value) { if (typeof(T).IsPrimitive || typeof(T) == typeof(string)) { return (T)Convert.ChangeType(value, typeof(T)); } throw new NotSupportedException("This serializer can only handle primitive types and strings. Please implement your own IObjectSerializer for more complex scenarios."); } /// /// Returns the value so that it can be serialized directly. /// /// Type to serialize from. /// Value to serialize. /// String representation of value. public string? Serialize(T value) { return value?.ToString(); } }