My c# model
public class Student
{
public string id{get;set;}
[System.Text.Json.Serializer.JsonPropertyName("ref")]
public int @ref{get;set;}
}
My ASP.Net Core API method
[HttpPost]
public async Task<IActionResult> Get([FromBody] Student stu)
{
var reference = stu.@ref;
//Here stu.@ref is always 0.
//JSON to C# model conversion doesnt work
}
Following is the request body
{
"id:"74A",
"ref":41
}
C# doesnt allow to declare variable name "ref", so i declared as "@ref" and decorated it with JsonPropertyName("ref"). However json to c# model deserialsation doesnt map ref to @ref.
Any solution or work around.
CodePudding user response:
You JSON string is missing a " after id and therefore it is not parsing it correctly since it is invalid. Once you get the correct JSON string, then you should be able to parse it correctly to your Student class.
You can verify if your JSON is valid here: https://jsonlint.com/
CodePudding user response:
Why you don' t change your property @ref to reference or something else? there are plenty names
public class Student
{
public string id{get;set;}
[System.Text.Json.Serializer.JsonPropertyName("ref")]
public int reference {get;set;}
}
