diff --git a/src/WWB.UnifyApi/Converter/DistanceFormatConverter.cs b/src/WWB.UnifyApi/Converter/DistanceFormatConverter.cs new file mode 100644 index 0000000..0c131fd --- /dev/null +++ b/src/WWB.UnifyApi/Converter/DistanceFormatConverter.cs @@ -0,0 +1,55 @@ +using Newtonsoft.Json; +using System; + +namespace WWB.UnifyApi.Converter +{ + public class DistanceFormatConverter : JsonConverter + { + /// + /// 是否开启自定义反序列化,值为true时,反序列化时会走ReadJson方法,值为false时,不走ReadJson方法,而是默认的反序列化 + /// + public override bool CanRead => false; + + /// + /// 是否开启自定义序列化,值为true时,序列化时会走WriteJson方法,值为false时,不走WriteJson方法,而是默认的序列化 + /// 类型等于long时才转换 + /// + /// + /// + 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(); + } + } + } +} \ No newline at end of file diff --git a/src/WWB.UnifyApi/WWB.UnifyApi.csproj b/src/WWB.UnifyApi/WWB.UnifyApi.csproj index 3fe5502..57cb698 100644 --- a/src/WWB.UnifyApi/WWB.UnifyApi.csproj +++ b/src/WWB.UnifyApi/WWB.UnifyApi.csproj @@ -3,7 +3,7 @@ netcoreapp3.1 WWB.UnifyApi - 2.0.4 + 2.0.5 my6521 NetCore3.1 MIT