skip to Main Content

I have input payload model (JSON) which contains JSON object by name class. I have to create a mapping class for JSON but since it contains the restricted keyword class, I cannot use it.

Below is the JSON to be mapped in the class:

"item": {
    "items": [
        {
            "department": {
                "id": "5",
                "refName": "test"
            },
            "class": {
                "id": "2",
                "refName": "test"
            }
        }
    ]
}

I have to use the above payload for the POST operation but since it contains the keyword class, I cannot use it. How can I achieve this?

2

Answers


  1. class is a C# reserve keyword. Instead, you should work with JsonPropertyAttribute (from Newtonsoft.Json) or JsonPropertyName (from System.Text.Json).

    For Newtonsoft.Json:

    using Newtonsoft.Json;
    
    [JsonProperty("class")]
    public Class Class { get; set; }
    

    For System.Text.Json:

    using System.Text.Json.Serialization;
    
    [JsonPropertyName("class")]
    public Class Class { get; set; }
    
    Login or Signup to reply.
  2. You also could use @class if you don’t want to use JsonProperty attribute.

    It can be read here:

    Keywords are predefined, reserved identifiers that have special meanings to the compiler. They can’t be used as identifiers in your program unless they include @ as a prefix. For example, @if is a valid identifier, but if isn’t because if is a keyword.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search