简体   繁体   中英

Attribute [JsonProperty] for rename property of DTO class in C#

[UPDATE 1]: Add My Controller and Application Layer Class

My Controller:

  [HttpPost]
        public async Task<ActionResult<FormulaItemsDTO>> Create(Create.Command command)
        {
            return await _mediator.Send(command);
        }

My Create Class in Application Layer

 public class Create
    {
        public class Command : IRequest<FormulaItemsDTO>
        {

            public int Id { get; set; }
            public string Title { get; set; }
            public string Description { get; set; }
            public List<FormulaInput> FormulaInputs { get; set; }
          
        }
        public class Handler : IRequestHandler<Command, FormulaItemsDTO>
        {
            private readonly PlantimsDbContext _context;
            public Handler(PlantimsDbContext context)
            {
                _context = context;
            }
            public async Task<FormulaItemsDTO> Handle(Command request, CancellationToken cancellationToken)
            {

                using (var transaction = _context.Database.BeginTransaction())
                {
                    try
                    {

                        foreach (var item in request.FormulaInputs)
                        {
                            FormulaInput formulaInput = new FormulaInput();
                            formulaInput.FormulaId = item.FormulaId;
                            formulaInput.TagId = item.TagId;
                            formulaInput.Position = item.Position;
                            _context.FormulaInputs.Add(formulaInput);
                        }

                      
                        await _context.SaveChangesAsync();
                        transaction.Commit();

                        return null;
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                        throw new Exception("problem saving change");
                    }
                }
            }

        }
    }

I have a DTO class and I want to map that class to a JSON request. I added JsonProperty from Newtonsoft to my DTO class but doesn't work. After sending the request through Postman, FormulaInputs is null when callign the EndPoint in the Contoller.

public class FormulaItemsDTO
    {
        public int Id { get; set; }
        [JsonProperty(PropertyName = "formula_inputs")
        public List<FormulaInput> FormulaInputs{ get; set; }
    
    }

JSON file:

{
  "formula_inputs": [
    {
      "key": "tagP051001FI0071PV",
      "tag_id": "P051001FI0071PV",
      "position": "B3",
      "column": "B"
    },
    {
      "key": "tagP051001FI0076PV",
      "tag_id": "P051001FI0076PV",
      "position": "C3",
      "column": "C"
    },
    {
      "key": "tagP051001FI0077PV",
      "tag_id": "P051001FI0077PV",
      "position": "D3",
      "column": "D"
    }
  ]
}

Unless you have explicitly switched to use Newtonsoft.Json as your JSON serializer, the default with ASP.NET Core 3 is to use the new JSON serializer System.Text.Json built into .NET Core, which has a smaller feature set but more focus on performance.

In that case, you cannot use the JSON attributes that come with Newtonsoft.Json but you will have to use the attributes that are in the System.Text.Json namespaces. In your particular case, you will have to use the [JsonPropertyName] attribute :

public class FormulaItemsDTO
{
    public int Id { get; set; }

    [JsonPropertyName("formula_inputs")
    public List<FormulaInput> FormulaInputs { get; set; }
}

You can read more about the differences between Newtonsoft.Json and System.Text.Json in the documenation . If you want to switch back to the Newtonsoft.Json serializer, which is a thing that you might need to do if you have to rely on more advanced features, then you can follow the migration guide to 3.0 and simply switch back.

You need to remove underscore from your Json array name "formula_inputs" . Then request data would be mapped to FormulaInputs collection inside your DTO class FormulaItemsDTO .

And no need to use JsonProperty attribute.

Update

If it is required to not chnage the Json formatting, as in this case array name is having underscore . Then add naming strategy in your Startup.cs inside ConfigureServices

services.AddControllers()
.AddNewtonsoftJson(options =>
{
    options.SerializerSettings.ContractResolver = new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy() };
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM