-2

My c# model

public class Student
{
  public string id{get;set;}
  [System.Text.Json.Serialization.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.

MARKAND Bhatt
  • 2,428
  • 10
  • 47
  • 80
  • 1
    Seems to be invalid json. Have you tried https://json2csharp.com ? – Oliver Jan 21 '22 at 11:25
  • 1
    Works on [my internet](https://dotnetfiddle.net/Yt7ofY). – Oliver Jan 21 '22 at 11:29
  • 1
    "Here stu.@ref is always 0." but what about stu.id ? – Serge Jan 21 '22 at 11:39
  • stu.id is "74A". Json to c# model works for id property – MARKAND Bhatt Jan 23 '22 at 12:42
  • 2
    Please post your actual code. `System.Text.Json.Serializer.JsonPropertyName` is not the right namespace, instead of `Serializer` it should be `Serialization`, which leads me to think there might be other problems as well. Do know that the *actual* property name of that property will be just `ref`, the `@` prefix is just to get the compiler to not treat it as the reserved keyword, the `@` will not actually be a part of the property name. – Lasse V. Karlsen Jan 24 '22 at 08:25
  • @LasseV.Karlsen I have updated the namespace. – MARKAND Bhatt Jan 25 '22 at 04:48

2 Answers2

2

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/

Rahul Sharma
  • 7,768
  • 2
  • 28
  • 54
1

Why you don' t change your property @ref to reference or something else? there are plenty another words, you don't need to use c# reserved

public class Student
{
  public string id{get;set;}
  [System.Text.Json.Serializer.JsonPropertyName("ref")]
  public int reference {get;set;}
}
Serge
  • 40,935
  • 4
  • 18
  • 45