I have a model class with a few properties named with all caps divided by underscores (e.g. APPOINTMENT_CHECKIN_TIME
). A controller Get method returns an instance of this class. But the JSON returned to the client has parts of property names converted to lowercase, like appointmenT_CHECKIN_TIME
. What can be causing this, and how to avoid this (e.g. make it appointmentCheckinTime
or at least the same as original)?
CodePudding user response:
Customize json property name:
[JsonPropertyName("appointmentCheckinTime")]
public DateTime APPOINTMENT_CHECKIN_TIME { get; set; }
Or customize the option to rename all json property names:
var serializeOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
jsonString = JsonSerializer.Serialize(myObject, serializeOptions);
Or define a global renaming policy:
using System.Text.Json;
namespace SystemTextJsonSamples
{
public class UpperCaseNamingPolicy : JsonNamingPolicy
{
public override string ConvertName(string name) =>
name.ToUpper();
}
}
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = new UpperCaseNamingPolicy(),
WriteIndented = true
};
jsonString = JsonSerializer.Serialize(myObject, options);
CodePudding user response:
Add this configuration in Program.cs(.Net 6)
builder.Services.AddMvc().AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = null; });