DD.WellWorkover.Cloud/AsbCloudWebApi/Converters/JsonValueJsonConverter.cs

74 lines
2.1 KiB
C#
Raw Normal View History

using System;
2023-03-31 11:26:42 +05:00
using System.Globalization;
using System.Text.Json.Serialization;
using System.Text.Json;
using AsbCloudApp.Data.GTR;
2024-08-19 10:01:07 +05:00
namespace AsbCloudWebApi.Converters;
public class JsonValueJsonConverter : JsonConverter<JsonValue>
2023-03-31 11:26:42 +05:00
{
2024-08-19 10:01:07 +05:00
public override JsonValue Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
2023-03-31 11:26:42 +05:00
{
2024-08-19 10:01:07 +05:00
if (reader.TokenType == JsonTokenType.String)
2023-03-31 11:26:42 +05:00
{
2024-08-19 10:01:07 +05:00
var stringVal = reader.GetString() ?? string.Empty;
return new JsonValue(stringVal);
}
2023-03-31 11:26:42 +05:00
2024-08-19 10:01:07 +05:00
if (reader.TokenType == JsonTokenType.Number)
{
if (reader.TryGetInt32(out int intVal))
return new JsonValue(intVal);
2023-03-31 11:26:42 +05:00
2024-08-19 10:01:07 +05:00
if (reader.TryGetDouble(out double doubleVal))
return new JsonValue((float)doubleVal);
2023-03-31 11:26:42 +05:00
}
2024-08-19 10:01:07 +05:00
throw new FormatException($"Wrong format at position {reader.Position}");
}
2023-03-31 11:26:42 +05:00
2024-08-19 10:01:07 +05:00
public override void Write(Utf8JsonWriter writer, JsonValue value, JsonSerializerOptions options)
{
if (value.Value is string strValue)
{
writer.WriteStringValue(FormatString(strValue));
return;
}
2023-03-31 11:26:42 +05:00
2024-08-19 10:01:07 +05:00
if (value.Value is int intValue)
{
writer.WriteNumberValue(intValue);
return;
}
2023-03-31 11:26:42 +05:00
2024-08-19 10:01:07 +05:00
if (value.Value is short shortValue)
{
writer.WriteNumberValue(shortValue);
return;
}
2023-03-31 11:26:42 +05:00
2024-08-19 10:01:07 +05:00
if (value.Value is float floatValue)
{
writer.WriteRawValue(floatValue.ToString("#0.0##", CultureInfo.InvariantCulture), true);
return;
}
2023-03-31 11:26:42 +05:00
2024-08-19 10:01:07 +05:00
if (value.Value is double doubleValue)
{
writer.WriteRawValue(doubleValue.ToString("#0.0##", CultureInfo.InvariantCulture), true);
return;
2023-03-31 11:26:42 +05:00
}
2024-08-19 10:01:07 +05:00
var typeName = value.Value.GetType().Name;
throw new NotImplementedException($"{typeName} is not supported type for WITS value");
2023-03-31 11:26:42 +05:00
}
2024-08-19 10:01:07 +05:00
private static string FormatString(string value)
=> value
.Replace("\"", "")
.Trim()
.Replace("\r", "")
.Replace("\n", "");
2023-03-31 11:26:42 +05:00
}