0

I'm tried to object a JSON with System.Text.Json from my class. I have a base class called Element that is defined like this

public interface IElement
{
    public string? Type { get; set; }
    public string? Name { get; set; }
}

Then, I have few classes that inherit from it, for example

public class Textbox : IElement
{
    [JsonPropertyName("type")]
    public virtual string? Type { get; set; }
    [JsonPropertyName("name")]
    public string? Name { get; set; }

    [JsonPropertyName("text")]
    public string? Text { get; set; }
}

public class Radiobutton : IElement
{
    [JsonPropertyName("type")]
    public virtual string? Type { get; set; }
    [JsonPropertyName("name")]
    public string? Name { get; set; }

    [JsonPropertyName("choises")]
    public List<string> Choises = new List<string>();
}

Now, I want to have a class that defines the form with all the elements

public class Form
{
    [JsonPropertyName("elements")]
    public List<IElement> Elements { get; set; } = new List<IElement>();
}

After that, I define the form

Form form = new Form()
{
    Elements = new List<IElement>()
    {
        new Textbox() { Name = "txt1", Type = "Textbox", Text = "One" },
        new Radiobutton() { 
            Name = "radio1", Type = "Radiobutton",
            Choices = new List<string>() { "One", "Two", "Three" }}
    }
};

If I create the JSON from this object, it has only the common fields

{
  "elements": [
    {
      "type": "Textbox",
      "name": "txt1",
    },
    {
      "type": "Radiobutton",
      "name": "radio1",
    }
  ]
}

The fields Text for the Textbox or Choices for the Radiobutton are ignored. I read the Microsoft documentation: I tried the code

jsonString = JsonSerializer.Serialize<object>(weatherForecast, options);

but I obtained the same result.

How can I create the JSON with all the details of the Form object regardless of the type of Element? Viceversa, when I have the JSON, how can I deserialize it in the Form class?

Enrico
  • 3,592
  • 6
  • 45
  • 102
  • *If I create the JSON from this object, it has only the common fields*, of course it is the expected behavior due to the concept of inheritance, upcasting in this case. – Soner from The Ottoman Empire Aug 19 '22 at 11:55
  • My usuall advise is to forget about Text.Json , use Newtonsoft.Json – Serge Aug 19 '22 at 12:47
  • I have to say that `System.Text.Json` is working quite well and better than `Newtonsoft.Json`. I added a help on here https://stackoverflow.com/questions/58074304/is-polymorphic-deserialization-possible-in-system-text-json – Enrico Aug 19 '22 at 22:39

1 Answers1

-1

Try this:

options = new JsonSerializerOptions
{
    WriteIndented = true
};

jsonString = JsonSerializer.Serialize(weatherForecast, weatherForecast.GetType(), options);