简体   繁体   中英

How to remove trailing zeros of nullable decimal in WebApi IActionResult Ok() function?

I have a sqlSever BDD that store some tables with column like decimal(12,6) and it store values like that ie : 1.000000 for only "1" he adds trailing zero automaticly. And when i take those values with linq and return an IActionResult with Ok(myObjectToSerializeInJson) function from webApi .net core 2.2 It results a json that looks like this :

{
"glu": 43.2,
"suc": 5.6,
"lip": null,
"agSat": 17.4,
"pro": 7.1,
"alc": 0,
"orga": 0,
}

But it was before i decided to upgrade some nuget packages that brings me to latest version of json.net (12.0.1) and now the same request return those trailing zeros...

{
"glu": 43.200000,
"suc": 5.600000,
"lip": null,
"agSat": 17.400000,
"pro": 7.100000,
"alc": 0.000000,
"orga": 0.000000,
}

Is it possible to keep the old behavior ?

Thanks for your replies guys, it helps me a lot :)

Finally i've added an annotation on each nullable decimal? members of my TDO objects that i thought they were required for my needs. It's look like this :

[JsonConverter(typeof(DecimalJsonConverter))]
public decimal? FielDecimalX { get; set; }

I've wrote a class to handle the conversion like in this solution

    public class DecimalJsonConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(decimal);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
            JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return null;
            }
            else
            {
                return Convert.ToDecimal(reader.Value, CultureInfo.InvariantCulture);
            }
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteRawValue(((decimal)value).ToString("G6", CultureInfo.InvariantCulture));
        }
    }

I took "G6" for my needs. If a value is greater than 5 decimal the output is x.yE-05 for a decimal value 0.0000xy but javascript reconize correctly this format number.

So output from my API .net core 2.2 returns this json :

{
"eau": 7.83,
"naCl": 0.5,
"orga": 7.2E-05,
"k1": null,
}

Hope that performance are not broken by this change, but i don't see any problems. Thus, i can save payload on my requests. Hope it helps !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM