码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2020-06-07 19:23:38      阅读:114      评论:0      收藏:0      [点我收藏+]

标签: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
    {
        ///// <summary>
        ///// 实现首字母小写
        ///// </summary>
        ///// <param name="propertyName"></param>
        ///// <returns></returns>
        //protected override string ResolvePropertyName(string propertyName)
        //{
        //    return propertyName.Substring(0, 1).ToLower() + propertyName.Substring(1);
        //}

        /// <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>
        /////   Creates a Newtonsoft.Json.Serialization.JsonProperty for the given System.Reflection.MemberInfo.
        ///// </summary>
        ///// <param name="type"></param>
        ///// <param name="memberSerialization"></param>
        ///// <returns></returns>
        //protected override IList<JsonProperty> 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
{
    /// <summary>
    /// Long类型Json序列化重写
    /// 在js中传输会导致精度丢失,故而在序列化时转换成字符类型
    /// </summary>
    public class JsonConverterLong : JsonConverter
    {
        /// <summary>
        /// 是否可以转换
        /// </summary>
        /// <param name="objectType"></param>
        /// <returns></returns>
        public override bool CanConvert(Type objectType)
        {
            return true;
        }

        /// <summary>
        /// 读json
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="objectType"></param>
        /// <param name="existingValue"></param>
        /// <param name="serializer"></param>
        /// <returns></returns>
        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;
            }
        }

        /// <summary>
        /// 写json
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="value"></param>
        /// <param name="serializer"></param>
        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";

代码如下:
/// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services"></param>
        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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!