0

I am writing a service to consume JSON that I have no control over. One property in this JSON can either be a number or a string, so input can either look like:

{"event_type":"status","value":"ok"}

or

{"event_type":"status","value":-253}

I have a record type in my code which I want to deserialise into:

public record StatusMessage(
    [property: JsonPropertyName("event_type")] string EventType, 
    [property: JsonPropertyName("value")] string StatusValue)

As expected this works fine when I attempt the deserialise the Json.String variant but the Json.Number variant blows up with System.InvalidOperationException: Cannot get the value of a token type 'Number' as a string..

I am aware that I can write a custom JsonConverter for StatusMessage but am wondering if there's any other way?

Dutts
  • 5,781
  • 3
  • 39
  • 61

0 Answers0