TribufuDotNet/Source/Tribufu.Serialization/DecimalStringConverter.cs
Guilherme Werner 7e8e192dc3
Migrate to new tribufu project structure (#2)
* Migrate to new tribufu project structure

* Update .gitignore

* Remove old api files

* Update Directory.Build.props

* Rename solution
2026-06-21 12:27:05 -03:00

32 lines
1 KiB
C#

// Copyright (c) Tribufu. All Rights Reserved.
// SPDX-License-Identifier: MIT
using Newtonsoft.Json;
using System;
using System.Globalization;
namespace Tribufu.Serialization
{
public class DecimalStringConverter : JsonConverter<decimal>
{
public override decimal ReadJson(JsonReader reader, Type objectType, decimal existingValue, bool hasExistingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.String && decimal.TryParse(reader.Value?.ToString(), out var result))
{
return result;
}
if (reader.TokenType == JsonToken.Integer)
{
return Convert.ToUInt64(reader.Value);
}
throw new JsonSerializationException($"Unexpected token {reader.TokenType} when parsing decimal.");
}
public override void WriteJson(JsonWriter writer, decimal value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString(CultureInfo.InvariantCulture));
}
}
}