I want my ASP.NET Web API to return a JSON response with spaces in property names. Currently when I am testing it using Postman, I am getting response in this format:
[
{
"appId": 1,
"appName": "app1"
},
{
"appId": 2,
"appName": "app2"
}
]
But I would like my Web API to return the response in the format shown here, because in the FE I am reading the column names dynamically and displaying as it it just by converting it to uppercase
[
{
"appId": 1,
"app Name": "app1"
},
{
"appId": 2,
"app Name": "app2"
}
]
To achieve this, I tried converting my model to this format:
public class MyApp
{
public int AppId {get; set;}
[JsonProperty(PropertyName = "App Name")]
public string AppName {get; set;}
}
But I still see that the response returned by my API uses the property as appName
.
How can I get a JSON property with a space in them?
Are you using newtonsoft
or System.Text.Json
as default serialization. Try System.Text.Json
attribute JsonPropertyName
.
could you please share your code
DTO With JsonPropertyName Attribute
using System.Text.Json.Serialization;
public class UserDTO
{
public Guid Id { get; init; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
[JsonPropertyName("Terms And Conditions Agreed")]
public bool TermsAndConditionsAgreed { get; set; }
}
JSON Options Setup
builder.Services.Configure<JsonOptions>(opt =>
{
opt.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
opt.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
opt.SerializerOptions.PropertyNameCaseInsensitive = true;
opt.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
opt.SerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
});