.Net Core 配置之long类型 前端精度丢失和时间格式设置

2021-02-09 11:18

阅读:372

标签:ase   space   object   one   namespace   format   api   turn   start   

在很多项目中,都采用的前后端分离的方式进行开发,经常遇到后台的long精度的数据到前端丢失不准确,显示效果为long类型(19位)的后几位为000,此时需要对long的字段进行设置,改变默认的返回类型,由long类型改变为string类型。所以需要全局自定义修改long类型的返回类型

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;

namespace NetCore3WebApiTemplate.Utility
{
    public class CustomContractResolver : CamelCasePropertyNamesContractResolver
    {
        ///// 
        ///// 实现首字母小写
        ///// 
        ///// 
        ///// 
        //protected override string ResolvePropertyName(string propertyName)
        //{
        //    return propertyName.Substring(0, 1).ToLower() + propertyName.Substring(1);
        //}

        /// 
        /// 对长整型做处理
        /// 
        /// 
        /// 
        protected override JsonConverter ResolveContractConverter(Type objectType)
        {
            if (objectType == typeof(long))
            {
                return new JsonConverterLong();
            }
            return base.ResolveContractConverter(objectType);
        }

        ///// 
        /////   Creates a Newtonsoft.Json.Serialization.JsonProperty for the given System.Reflection.MemberInfo.
        ///// 
        ///// 
        ///// 
        ///// 
        //protected override IList CreateProperties(Type type, MemberSerialization memberSerialization)
        //{
        //    return type.GetProperties()
        //            .Select(p =>
        //            {
        //                var jp = base.CreateProperty(p, memberSerialization);
        //                jp.ValueProvider = new NullToEmptyStringValueProvider(p);
        //                return jp;
        //            }).ToList();
        //}
    }
}

  

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace NetCore3WebApiTemplate.Utility
{
    /// 
    /// Long类型Json序列化重写
    /// 在js中传输会导致精度丢失,故而在序列化时转换成字符类型
    /// 
    public class JsonConverterLong : JsonConverter
    {
        /// 
        /// 是否可以转换
        /// 
        /// 
        /// 
        public override bool CanConvert(Type objectType)
        {
            return true;
        }

        /// 
        /// 读json
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            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;
            }
        }

        /// 
        /// 写json
        /// 
        /// 
        /// 
        /// 
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
                writer.WriteValue(value);
            else
                writer.WriteValue(value + "");
        }
    }
}

 

在startup的ConfigureServices中设置

  序列化的格式

options.SerializerSettings.ContractResolver = new CustomContractResolver();

时间格式:
options.SerializerSettings.DateFormatString = "yyyy‘-‘MM‘-‘dd‘ ‘HH‘:‘mm‘:‘ss";

代码如下:
/// 
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// 
        /// 
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(ops =>
            {
              
            }).SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddNewtonsoftJson(options =>
             {
                 //设置时间格式
                 options.SerializerSettings.DateFormatString = "yyyy‘-‘MM‘-‘dd‘ ‘HH‘:‘mm‘:‘ss";
                 options.SerializerSettings.ContractResolver = new CustomContractResolver();
             });
}

  

注意:

AddNewtonsoftJson 方法需要应用Microsoft.AspNetCore.Mvc.NewtonsoftJson

.Net Core 配置之long类型 前端精度丢失和时间格式设置

标签:ase   space   object   one   namespace   format   api   turn   start   

原文地址:https://www.cnblogs.com/binbinxu/p/13061561.html


评论


亲,登录后才可以留言!