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
You have to change the default property naming policy on the json serialization options.
By default it's set to camel case but if you set it to null
, the property names are to remain unchanged (or remain as you wrote on your class).
Simply add this to your Startup.cs
:
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = null;
});
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)
jsonSettings.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)
jsonSettings.ContractResolver = new DefaultContractResolver();
});
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.