I have the following type:
public class Product : Dictionary<string, object>
{
[JsonInclude]
public string ProductId { get; set; }
public Product(string productId) : base()
{
ProductId = productId;
}
}
When serialising using System.Text.Json it does not include the properties (ie ProductId).
Adding or removing the [JsonInclude] does not seem to make any effect.
Test case:
[Fact]
public void SimpleTest()
{
var p = new Product("ABC123");
p["foo"] = "bar";
var json = JsonSerializer.Serialize(p);
Assert.Contains("productId", json, StringComparison.OrdinalIgnoreCase);
}
And output received:
{"foo":"bar"}
How do I make it include my custom properties on my type during serialisation? (note: don't care about deserialisation).
System.Text.Jsononly serializes the dictionary keys and values not the c# properties, as 1) there might be a key with the same name as a property, and 2) You probably don't want the "standard" properties likeCountandIsReadOnlyto be serialized. I can't find anywhere in the MSFT docs where this is stated, however Newtonsoft is documented to behave this way as isDataContractJsonSerializerandJavaScriptSerializer.System.Text.Jsonseems to have followed precedent.Productdoesn't inherit fromDictionarybut instead has a[System.Text.Json.Serialization.JsonExtensionData] public Dictionary<string, object> Properties { get; set; }property. The[JsonExtensionData]attribute causes the dictionary properties to be included as part of the parent object when serializing.JsonConverter. (According to the docs forJsonIncludeWhen applied to a property, indicates that non-public getters and setters can be used for serialization and deserialization. So it isn't relevant here asProductIdalready has public getters and setters.)