1

I am facing an issue by converting JSON to c# using JSON converter. where I have a field decimal value is 10000 when converting the value is 10000.0 — how to restrict that?

using System;
using Newtonsoft.Json;


public class Program
{
    public class Employee  
{  
    public int ID { get; set; }  
    public string Name { get; set; }  
    public decimal? Salary { get; set; }  
}  
    public static void Main()
    {
         // Serializaion  
    Employee empObj = new Employee();  
    empObj.ID = 1;  
    empObj.Name = "Manas";  
    empObj.Salary = 10000;

    // Convert Employee object to JOSN string format   
    string jsonData = JsonConvert.SerializeObject(empObj);  

    Console.WriteLine(jsonData); 
    }
}

Actual Result:

{"ID":1,"Name":"Manas","Salary":10000.0}

Expected Result:

{"ID":1,"Name":"Manas","Salary":10000}
AJF
  • 11,767
  • 2
  • 37
  • 64
Ramesh
  • 21
  • 4

1 Answers1

1

Try using a custom converter, see the snippet below.

using System;
using System.Globalization;
using Newtonsoft.Json;


public class Program
{
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }

        [JsonConverter(typeof(CustomDecimalConverter))]
        public decimal? Salary { get; set; }
    }
    public static void Main()
    {
        // Serializaion  
        var empObj = new Employee { ID = 1, Name = "Manas", Salary = 10000 };

        // Convert Employee object to JOSN string format   
        var jsonData = JsonConvert.SerializeObject(empObj);

        Console.WriteLine(jsonData);
        Console.ReadLine();
    }

    public class CustomDecimalConverter : JsonConverter    
    {    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)    
        {    
            writer.WriteValue(((decimal)value).ToString(CultureInfo.InvariantCulture));    
        }

        public override bool CanRead => false;

        public override bool CanConvert(Type objectType)    
        {    
            return objectType == typeof(decimal) || objectType == typeof(decimal?);    
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)    
        {    
            throw new NotImplementedException();    
        }       
    }
}
A.M. Patel
  • 334
  • 2
  • 9