Home > Enterprise >  How to set WebApi to default to UpperCamelCase (Json)
How to set WebApi to default to UpperCamelCase (Json)

Time:01-19

I would like to configure the default serializer of the WebApi so it should keep the name of the fields from the class.

namespace ChimuLambdaApi.Controllers;

[ApiController]
[Microsoft.AspNetCore.Mvc.Route("[controller]")]
public class V1Controller : ControllerBase {
    private readonly ILogger<V1Controller> _logger;

    public V1Controller(ILogger<V1Controller> logger) => _logger = logger;

    [Microsoft.AspNetCore.Mvc.HttpGet("map")]
    public Beatmap GetBeatmap(long id) {
        return new Beatmap() { };
    }
}


namespace ChimuLambdaApi;

public class Beatmap {
    public int BeatmapId { get; set; }
    public double BPM { get; set; }
    public float AR { get; set; }
    public float OD { get; set; }
    public float CS { get; set; }
    public float HP { get; set; }
    public string File { get; set; }
}

This is what i got from WebApi results.

   "beatmapId": 0,
   "bpm": 0,
   "ar": 0,
   "od": 0,
   "cs": 0,
   "hp": 0,
   "file": "string"

This is what i want to get.

   "BeatmapId": 0,
   "BPM": 0,
   "AR": 0,
   "OD": 0,
   "CS": 0,
   "HP": 0,
   "File": "string"

CodePudding user response:

You can configure the JsonOptions in your Program.cs. Using the following configuration of PropertyNameCaseInsensitive and PropertyNamingPolicy you can achieve the functionality you want:

builder.Services.Configure<JsonOptions>(o =>
{
    o.JsonSerializerOptions.PropertyNameCaseInsensitive = false;
    o.JsonSerializerOptions.PropertyNamingPolicy = null;
});

This will configure the serializer to match the casing of your class properties. If you wanted different casing you could use [JsonPropertyName] attribute on the properties.

You could instead configure the same properties after AddControllers using builder.Services.AddControllers().AddJsonOptions(...).

example


However, the majority of clients/serializers are configured to use camelCase by default when sending/receiving requests so you could be introducing more work for yourself (or others using your API) in future.

CodePudding user response:

You can use like this. Maybe the code can be written more effectively.

[Microsoft.AspNetCore.Mvc.HttpGet("map")]
public string GetBeatmap(long id) {
   return JsonConvert.SerializeObject(new BeatMap(), Formatting.Indented, new JsonSerializerSettings
      {
         ContractResolver = new CamelCasePropertyNamesContractResolver()
      });
}
  •  Tags:  
  • Related