How to include (or replace) static properties in System.Text.Json serialization?

Viewed 416

I have some object like this:

public class ResponseBase
{
    public string eventType { get; }
    public string eventSourceGuid { get; }
}

public class QueryDevicesResponse : ResponseBase
{
    public new static string eventType { get => "queryDevicesResponse"; }
    public new string eventSourceGuid { get => "0"; }
    public EventData eventData { get; set; }
}

eventType field is static because I'm trying to:

  • minimize lines of code
  • use it like "application-wide" string stored (in source code) together with DTO class definition, and use it in some switch and if statements without instantiating QueryDevicesResponse.

When I call:

QueryDevicesResponse queryDevicesResponse = QueryDevicesResponse.Mock();
JsonSerializer.Serialize.JsonSerializer.Serialize(queryDevicesResponse);

I'm getting JSON without eventType field. I guess this is because field is static.

Can I change JsonSerializer behavior to include also static fields?

This is similar question, but this is about Newtonsoft.Json:

Why can't JSON .Net serialize static or const member variables?

Alternatively:

How can I replace static modifier to get similar behavior and keep code small?

0 Answers
Related