FlexitimeTracker/FlexitimeUI/Infrastructure/Functions/NonEmptyStringConverter.cs
2023-04-11 20:17:20 +01:00

45 lines
1.4 KiB
C#

using System;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json;
namespace Infrastructure.Functions
{
[ExcludeFromCodeCoverage]
public class NonEmptyStringConverter : JsonConverter
{
public override bool CanConvert(Type objectType) =>
objectType == typeof(string);
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var stringValue = (string)value;
writer.WriteValue(stringValue);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType != JsonToken.String)
{
throw CreateException($"Expected string value, but found {reader.TokenType}.", reader);
}
var stringValue = (string)reader.Value;
if (string.IsNullOrWhiteSpace(stringValue))
{
throw CreateException("Non-empty string required.", reader);
}
return stringValue;
}
private static Exception CreateException(string message, JsonReader reader)
{
var info = (IJsonLineInfo)reader;
return new JsonSerializationException($"{message} Path: '{reader.Path}', Line: {info.LineNumber}");
}
}
}