2

I have a .net framework 4.7 MVC project using the NuGet Newtonsoft as a serializer. I would like to serialize a long property as a string. I am trying this solution but I cannot find what happened and does not work properly with the accepted answer.

I have a test endpoint

[RoutePrefix("Test")]
    public class TestController : Controller
    {
        [HttpGet,Route("Test2")]
        public JsonResult Test2()
        {
            var customer = new Customer
            {
                Id = long.MaxValue,
                Name = "test15"
            };
            return new JsonResult { Data = customer, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
    }

Also, I have the class person and a custom converter

public class Customer
    {
        [JsonConverter(typeof(Int64JsonConverter))]
        public long Id { get; set; }
        public string Name { get; set; }
    }

    class Int64JsonConverter : JsonConverter<long>
    {
        public override long ReadJson(JsonReader reader, Type objectType, long existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            if (reader.Value == null)
                return 0;

            return long.Parse(reader.Value.ToString());
        }
        public override void WriteJson(JsonWriter writer, long value, JsonSerializer serializer)
        {
            // convert to string instead, javascript number size is smaller than long
            writer.WriteValue(value.ToString());
        }
    }

My first try is to annotate the property with the converter. The second try is to remove the annotation from the property and set in WebApiConfig my custom converter

public class WebApiConfig
    {
        public static void Register(HttpConfiguration configuration)
        {

            configuration.MapHttpAttributeRoutes();

            configuration.Routes.MapHttpRoute(
                "API Default",
                "api/{controller}/{id}",
                new { id = RouteParameter.Optional });
            //configuration.Formatters.JsonFormatter.SerializerSettings.Converters = new List<JsonConverter> { new Int64JsonConverter(), new Int64NullableJsonConverter() };
            configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new Int64JsonConverter());
        }
    }

Also my global asax class is

public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            HttpConfiguration config = GlobalConfiguration.Configuration;
            config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new Int64JsonConverter());
            //config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new Int64NullableJsonConverter());
        }
    }

I try to set the custom formatters with various ways like

//1) First try
            //var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            //json.SerializerSettings.Converters = GetJsonConverters();

        //2)Second try
        //HttpConfiguration config = GlobalConfiguration.Configuration;
        //config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new Int64JsonConverter());
        //config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new Int64NullableJsonConverter());

        //3) Third try
        //JsonConvert.DefaultSettings = () => new JsonSerializerSettings
        //{
        //  Formatting = Formatting.Indented,
        //  TypeNameHandling = TypeNameHandling.Objects,
        //  ContractResolver = new CamelCasePropertyNamesContractResolver(),
        //  Converters = GetJsonConverters()
        //};

        //4) Fourth try
        //HttpConfiguration config = new HttpConfiguration();
        //config.Formatters.JsonFormatter.SerializerSettings.Converters = new List<JsonConverter> { new Int64JsonConverter(), new Int64NullableJsonConverter() };

        //5) Fifth try
        //var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
        //json.SerializerSettings.Converters.Add(new Int64JsonConverter());

but always the result is the long property in not converted to string I get

{
    "Id": 9223372036854775807,
    "Name": "test15"
}
dimmits
  • 1,999
  • 3
  • 12
  • 30
  • What's the expected value? – Panagiotis Kanavos Sep 24 '21 at 11:14
  • @PanagiotisKanavos I expect "Id": "9223372036854775807" because i convert it to string – dimmits Sep 24 '21 at 11:16
  • ASP.NET MVC doesn't use Json.NET, it uses the ancient JavascriptSerializer. Json.NET is used in Web API. ASP.NET Core started with JSON.NET before switching to System.Text.Json – Panagiotis Kanavos Sep 24 '21 at 11:20
  • @PanagiotisKanavos but in JsonConverter, JsonReader, JsonWriter, JsonSerializer I have imported these from the NuGet Newtonsoft? What I don't understand? – dimmits Sep 24 '21 at 11:33
  • *MVC itself* doesn't use JSON.NET, so any converters you create won't be used. You'll have to use JSON.NET yourself. Check the answers to [Using JSON.NET as the default JSON serializer in ASP.NET MVC 3 - is it possible?](https://stackoverflow.com/questions/7109967/using-json-net-as-the-default-json-serializer-in-asp-net-mvc-3-is-it-possible). If you migrate to ASP.NET Core MVC you won't have this problem – Panagiotis Kanavos Sep 24 '21 at 11:42

1 Answers1

0

You may implement ISerializable interface in your Customer class to specify how it will be serialized/deserialized

Andrey Golubev
  • 132
  • 1
  • 2
  • 8
  • Thanks for the reply ,I prefer something like global settings because we have many classes,but i am going to check and this solution – dimmits Sep 24 '21 at 11:33