0

I have the following model

public class SocioEconomicStudy : BaseModel
{
    public string Folio { get; set; }

    public string Craft { get; set; }

    public string RequestType {get;set;}
}

And I send the following json

{
     "folio" : "folio",
     "craft" : "craft,
     "request_type": "request_type"
}

But when received the properties with underscore are null, I've tried camel case Pascal case, but only with the lowercase + underscores is that the properties without underscore work.

Controller method:

[HttpPost]
public void Post([FromBody] SocioEconomicStudy study)
{
    var cancellationToken = new CancellationToken();
    _logger.LogInformation((study != null).ToString());
    _context.SocioEconomicStudyRepository.AddAsync(study, cancellationToken);
}

So only the properties without underscore are persisted, any ideas on how to solve this?

3
  • 1
    What json serializer do you use? Commented May 3, 2017 at 10:03
  • @RubenVardanyan I'm using the default serializer, Commented May 3, 2017 at 14:16
  • See the answer below Commented May 3, 2017 at 17:46

2 Answers 2

2

For the properties which not follow the naming rules you can add JsonProperty attribute, in your case your model should look like this

public class SocioEconomicStudy : BaseModel
{
    public string Folio { get; set; }

    public string Craft { get; set; }

    [JsonProperty("request_type")]
    public string RequestType { get; set; }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but if my model changes, or I need more models, I will also need to annotate every property with more than one word.
Yes you need to annotate every property or change the frontend part to send property named camel case
0

Adding the following to Startup.cs solved my problem

services.AddMvc()
        .AddJsonOptions(options =>
         {
             options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
         }); 

Now it accepts camelCase keys

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.