Home > Mobile >  Deserializing url-encoded-form-data with reserved word as variable name
Deserializing url-encoded-form-data with reserved word as variable name

Time:03-03

I am building a webhook in c# currently and one of the variables I'm supposed to receive is called "event" which is a reserved word in c#. How can I tell the controller to deserialize it as a different variable name. I tried doing it like I would with JSON (below), but it was unsuccessful.

public class WaiverPosted
{
    public string unique_id { get; set; }
    public string credential { get; set; }
    
    [JsonPropertyName("event")]
    public string _event { get; set; }
}

EDIT FOR CLARIFICATION: The data is coming in as www-url-form-encoded data. Here is the method header where it is deserialized.

[HttpPost]
[Route("createcustomer")]
public async Task<IActionResult> CreateCustomer([FromForm] WaiverPosted input)
{
     //DO SOMETHING
}

CodePudding user response:

Your code seems to be working just fine when I tested it. Here is my version:

using System.Text.Json;
using System.Text.Json.Serialization;

var json = @"{
    ""unique_id"": ""12345678"",
    ""credential"": ""username-and-password"",
    ""event"": ""some-event-value""
}";

var result = JsonSerializer.Deserialize<WaiverPosted>(json);

Console.WriteLine(result?.unique_id);
Console.WriteLine(result?.credential);
Console.WriteLine(result?._event);

public class WaiverPosted
{
    public string? unique_id { get; set; }
    public string? credential { get; set; }

    [JsonPropertyName("event")]
    public string? _event { get; set; }
}

Output:

12345678
username-and-password
some-event-value

CodePudding user response:

The trick is to tell the compiler to not treat that name as the reserved keyword event, and you do that with an at-sign, like this:

public string @event { get; set; }

Now, you might think this will be similar to using an underscore but that is not correct. The at-sign will actually not become part of the event name, it's just there to tell the compiler to not treat the next word as a reserved keyword, and instead treat it as an identifier.

Also note that everywhere you want to refer to this property, you likely have to keep using the at-sign prefix or that reference will not compile either.

Here's an example:

void Main()
{
    Console.WriteLine(nameof(@event));
    Console.WriteLine(nameof(_event));
}

public string @event { get; set; }
public string _event { get; set; }

Will output:

event
_event
  • Related