Skip to content

Commit

Permalink
添加json转换
Browse files Browse the repository at this point in the history
  • Loading branch information
my6521 committed Oct 17, 2021
1 parent 947de74 commit 0c4fbe1
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
50 changes: 50 additions & 0 deletions src/WWB.UnifyApi/Converter/LongToStringConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using Newtonsoft.Json;
using System;

namespace WWB.UnifyApi.Converter
{
public class LongToStringConverter : 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;
}

var cValue = value.ToString();
//长度大于等于19位的ID才返回String
if (cValue != null && (cValue.Length >= 15 || writer.Path.ToLower().Contains("id")))
{
writer.WriteValue(cValue);
}
else
{
writer.WriteValue(value);
}
}
}
}
5 changes: 3 additions & 2 deletions src/WWB.UnifyApi/WWB.UnifyApi.csproj
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<PackageId>WWB.UnifyApi</PackageId>
<Version>1.0.1</Version>
<Version>1.0.2</Version>
<Authors>my6521</Authors>
<Description>NetCore3.1</Description>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
Expand All @@ -13,5 +13,6 @@

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>
</Project>

0 comments on commit 0c4fbe1

Please sign in to comment.