C#C
C#2y ago
Sky

Newtonsoft.JSON ignore a JsonProperty

Hi there! I'm struggling at making my classes to correctly be serialized. I have an interface:
public interface IComponent
{
    public ComponentType ComponentType { get; }
    public List<IComponent> Children { get; }
    public IComponentClickEvent? ClickEvent { get; set; }
    public IComponentStyle Style { get; set; }
}

And its implementation:
public class TextComponent : IComponent
{
    
    [JsonProperty("text")]
    public string Text { get; set; }
    public TextComponent(string text, IComponentStyle? style)
    {
        if (string.IsNullOrWhiteSpace(text))
            throw new System.ArgumentException("Given text cannot be null or empty", nameof(text));
        
        Text = text;
    }
    
    [JsonProperty("type"), JsonConverter(typeof(ComponentTypeSerializer))]
    public ComponentType ComponentType { get; } = ComponentType.Text;
    public string Type { get; } = "text";
    
    [JsonProperty("extra")]
    public List<IComponent> Children { get; } = new();
    
    public IComponentClickEvent? ClickEvent { get; set; }
    public IComponentStyle Style { get; set; }
}

I'm also using this serializer:
public class ComponentTypeSerializer : JsonConverter<ComponentType>
{
    public override void WriteJson(JsonWriter writer, ComponentType value, JsonSerializer serializer)
    {
        writer.WriteValue(value.ToString().ToLower());
    }

    public override ComponentType ReadJson(JsonReader reader, Type objectType, ComponentType existingValue, bool hasExistingValue,
        JsonSerializer serializer)
    {
        throw new NotImplementedException("Deserializing ComponentType is not supported.");
    }
}

And I'm serializing my value this way:
var settings = new JsonSerializerSettings
{
    Converters = new JsonConverter[]
    {
        new Serializers.ComponentTypeSerializer(),
        new Serializers.ComponentColorSerializer()
    },
    NullValueHandling = NullValueHandling.Ignore,
    DefaultValueHandling = DefaultValueHandling.Ignore,
    Formatting = Formatting.None
};
return JsonConvert.SerializeObject(component, settings);

However, I am unable to get the type property working! It literally never shows when serializing my class.
For instance, I'm getting {"text": "Hello There", "extra":[]} when serializing new TextComponent("Hello There")
Can anyone help me about this? Thanks ^.^
Was this page helpful?