0

In .NET 6.0 application it uses Newtonsoft library for JSON serialization. It uses JsonProperty attribute for alias naming in response. However, it provides actual property name(FileName in our example rather it should be label) instead of alias name.

Controller:

public async Task<JsonResult> GetAllFiles(string appId)
    {var files = GetAFiles(appId); return Ok(files);}

Model:

[JsonProperty(PropertyName = "label")]
public string FileName { get; set; }

Expected Response:

[{"label":"test.pdf"}]
Manas Kumar
  • 2,411
  • 3
  • 16
  • 23
  • 1
    I am sure that `[JsonProperty(PropertyName = "label")]` will work with standalone Newtonsoft serialization in .NET 6. Are you sure you aren't actually using System.Text.Json as is the case in [Attribute JsonProperty works incorrect with .NET Core 3.1 when I use underscore symbol](https://stackoverflow.com/q/59914611)? Try adding `[System.Text.Json.Serialization.JsonPropertyName("label")]` to `FileName` to see if the problem resolves itself. Also, try looking through the answers to [JSON.Net serializer ignoring JsonProperty?](https://stackoverflow.com/q/8424151/3744182) to see if any apply. – dbc Jun 21 '22 at 04:53
  • Thank you. Your comment(added the library in Parent project) partially helps me – Manas Kumar Jun 22 '22 at 10:11

1 Answers1

-1

Root cause: JsonProperty attribute was getting ignored, so it was not applying. To resolve the issue, Newtonsoft library(same version) is added which was referred in other class library(Model).

Secondly, Microsoft.AspNetCore.Mvc.NewtonsoftJson nuget package is added in main project in Startup.cs with following code snippet:

services.AddMvcCore().AddNewtonsoftJson();

In Model

[JsonProperty(PropertyName = "label")]
public string FileName { get; set; }
Manas Kumar
  • 2,411
  • 3
  • 16
  • 23