85 lines
2.7 KiB
C#
85 lines
2.7 KiB
C#
using Newtonsoft.Json;
|
|
using Newtonsoft.Json.Serialization;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace YBDevice.Api
|
|
{
|
|
///<summary>
|
|
/// long类型处理
|
|
/// </summary>
|
|
//public class CustomContractResolver : CamelCasePropertyNamesContractResolver //默认为驼峰样式
|
|
public class CustomContractResolver : DefaultContractResolver //保持默认值
|
|
{
|
|
protected override string ResolvePropertyName(string propertyName)
|
|
{
|
|
return base.ResolvePropertyName(propertyName);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 对长整型做处理
|
|
/// </summary>
|
|
/// <param name="objectType"></param>
|
|
/// <returns></returns>
|
|
protected override JsonConverter ResolveContractConverter(Type objectType)
|
|
{
|
|
if (objectType == typeof(long))
|
|
{
|
|
return new JsonConverterLong();
|
|
}
|
|
return base.ResolveContractConverter(objectType);
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// 对于LONG类型的转换
|
|
/// </summary>
|
|
public class JsonConverterLong : JsonConverter
|
|
{
|
|
/// <summary>
|
|
/// 判断是否为Long类型
|
|
/// </summary>
|
|
/// <param name="objectType">类型</param>
|
|
/// <returns>为long类型则可以进行转换</returns>
|
|
public override bool CanConvert(Type objectType)
|
|
{
|
|
if (objectType == typeof(long))
|
|
return true;
|
|
return false;
|
|
}
|
|
|
|
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
|
|
{
|
|
if (value == null)
|
|
return;
|
|
string lvalue = value.ToString();
|
|
writer.WriteValue(lvalue);
|
|
}
|
|
|
|
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
|
|
{
|
|
//bool isNullable = IsNullableType(objectType);
|
|
//Type t = isNullable ? Nullable.GetUnderlyingType(objectType) : objectType;
|
|
//if (reader.TokenType == JsonToken.Null)
|
|
//{
|
|
// return null;
|
|
//}
|
|
//if (reader.TokenType == JsonToken.Integer)
|
|
//{
|
|
// return reader.Value.ToString();
|
|
//}
|
|
//return null;
|
|
if ((reader.ValueType == null || reader.ValueType == typeof(long?)) && reader.Value == null)
|
|
{
|
|
return null;
|
|
}
|
|
else
|
|
{
|
|
long.TryParse(reader.Value != null ? reader.Value.ToString() : "", out long value);
|
|
return value;
|
|
}
|
|
}
|
|
}
|
|
}
|