fix convert json int 1.0 => 1 in c# newtonsoft

0 thích 0 không thích
1 lượt xem
đã hỏi 26 Tháng 10, 2021 trong Lập trình C# bởi nguyenthao (7,300 điểm)
public class DecimalJsonConverter : JsonConverter<decimal>
{
    public override decimal ReadJson(JsonReader reader, Type objectType, 
        decimal existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, 
        decimal value, JsonSerializer serializer)
    {
        // Customise how you want the decimal value to be output in here
        // for example, you may want to consider culture
        writer.WriteRawValue(value.ToString());
    }
}

//use
var settings = new JsonSerializerSettings
{
    Converters = new[] { new DecimalJsonConverter() }
};

var json = JsonConvert.SerializeObject(1m, settings);

    

1 câu trả lời

0 thích 0 không thích
đã trả lời 18 Tháng 12, 2021 bởi nguyenthao (7,300 điểm)
 
Câu trả lời hay nhất
class DecimalJsonConverter : JsonConverter
    {
        public DecimalJsonConverter()
        {
        }

        public override bool CanRead
        {
            get
            {
                return false;
            }
        }

        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 bool CanConvert(Type objectType)
        {
            return (objectType == typeof(decimal) || objectType == typeof(float) || objectType == typeof(double));
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (DecimalJsonConverter.IsWholeValue(value))
            {
                writer.WriteRawValue(JsonConvert.ToString(Convert.ToInt64(value)));
            }
            else
            {
                writer.WriteRawValue(JsonConvert.ToString(value));
            }
        }

        private static bool IsWholeValue(object value)
        {
            if (value is decimal)
            {
                decimal decimalValue = (decimal)value;
                int precision = (Decimal.GetBits(decimalValue)[3] >> 16) & 0x000000FF;
                return precision == 0;
            }
            else if (value is float || value is double)
            {
                double doubleValue = (double)value;
                return doubleValue == Math.Truncate(doubleValue);
            }

            return false;
        }
    }

-- using

var jData = JsonConvert.SerializeObject(table, new DecimalJsonConverter());
...