Skip to content

Commit

Permalink
distanceformater
Browse files Browse the repository at this point in the history
  • Loading branch information
my6521 committed Dec 19, 2023
1 parent db66b4a commit 653b773
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
55 changes: 55 additions & 0 deletions src/WWB.UnifyApi/Converter/DistanceFormatConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
using Newtonsoft.Json;
using System;

namespace WWB.UnifyApi.Converter
{
public class DistanceFormatConverter : JsonConverter
{
/// <summary>
/// 是否开启自定义反序列化,值为true时,反序列化时会走ReadJson方法,值为false时,不走ReadJson方法,而是默认的反序列化
/// </summary>
public override bool CanRead => false;

/// <summary>
/// 是否开启自定义序列化,值为true时,序列化时会走WriteJson方法,值为false时,不走WriteJson方法,而是默认的序列化
/// 类型等于long时才转换
/// </summary>
/// <param name="objectType"></param>
/// <returns></returns>
public override bool CanConvert(Type objectType)
{
return objectType == typeof(long) || objectType == typeof(long?);
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException("Unnecessary because CanRead is false.The type will skip the converter.");
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
if (long.TryParse(value.ToString(), out long res))
{
if (res < 1000)
{
writer.WriteValue($"{res}m");
}
else
{
var sValue = (res / 1000).ToString("0.00");

writer.WriteValue($"{sValue}km");
}
}
else
{
writer.WriteNull();
}
}
}
}
2 changes: 1 addition & 1 deletion src/WWB.UnifyApi/WWB.UnifyApi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<PackageId>WWB.UnifyApi</PackageId>
<Version>2.0.4</Version>
<Version>2.0.5</Version>
<Authors>my6521</Authors>
<Description>NetCore3.1</Description>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
Expand Down

0 comments on commit 653b773

Please sign in to comment.