Search code examples
c#jsonentity-frameworkasp.net-coreasp.net-apicontroller

API Json response to C# Object with capital case properties first letter


I've made an API where after an Entity Framework elaboration I send an object serialized in Json.

My Object:

public class Package
{
    public int Items { get; set; }
    public string Code { get; set; }
    public string Description { get; set; }
    public double? Weight { get; set; }
    public string Size { get; set; }
    public string PackageType { get; set; }
}

The problem start when after recieve it (Xamarin app) the Json have the first letter lowercase, but I want deserialize it in the exact same class and it can't because the class have properties in capitalcase (C# standard). Now I'm using a horrible 'helper' class that have the properties in lowercase for translating it.

Any idea how to handle this and send the Json directly with capital case first letter?

Edit

I use ASP.NET web API Core and Newtonsoft.Json

In Xamarin app I use System.Text.Json


Solution

  • By default, ASP.NET Core encodes all JSON properties names in camel case, to match JSON conventions (see the announcement of the change on GitHub).

    If you want to keep the C# conventions, you need to change the default JSON serializer.

    In your Startup.cs, configure the MVC part like this (ASP.Net Core 3.0):

    services
        .AddMvc()
        .AddNewtonsoftJson(options =>
        {
            // don't serialize with CamelCase (see https://github.com/aspnet/Announcements/issues/194)
            options.SerializerSettings.ContractResolver = new JsonContractResolver();
        });
    

    For ASP.NET Core 2.0 :

    services
        .AddMvc()
        .AddJsonOptions(options =>
        {
            // don't serialize with CamelCase (see https://github.com/aspnet/Announcements/issues/194)
            options.SerializerSettings.ContractResolver = new DefaultContractResolver();
        });