using System.Runtime.InteropServices;
using Newtonsoft.Json;
namespace Dalamud.Common;
///
/// Converts a to and from a string (e.g. "FreeBSD").
///
public sealed class OSPlatformConverter : JsonConverter
{
///
/// Writes the JSON representation of the object.
///
/// The to write to.
/// The value.
/// The calling serializer.
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
}
else if (value is OSPlatform)
{
writer.WriteValue(value.ToString());
}
else
{
throw new JsonSerializationException("Expected OSPlatform object value");
}
}
///
/// Reads the JSON representation of the object.
///
/// The to read from.
/// Type of the object.
/// The existing property value of the JSON that is being converted.
/// The calling serializer.
/// The object value.
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
else
{
if (reader.TokenType == JsonToken.String)
{
try
{
return OSPlatform.Create((string)reader.Value!);
}
catch (Exception ex)
{
throw new JsonSerializationException($"Error parsing OSPlatform string: {reader.Value}", ex);
}
}
else
{
throw new JsonSerializationException($"Unexpected token or value when parsing OSPlatform. Token: {reader.TokenType}, Value: {reader.Value}");
}
}
}
///
/// Determines whether this instance can convert the specified object type.
///
/// Type of the object.
///
/// true if this instance can convert the specified object type; otherwise, false.
///
public override bool CanConvert(Type objectType)
{
return objectType == typeof(OSPlatform);
}
}