JsonObjectAttribute force object serialization

September 7, 2025 ยท View on GitHub

This sample uses Argon.JsonObjectAttribute to serialize a class that implements System.Collections.Generic.IEnumerable<T> as a JSON object instead of a JSON array.

[JsonObject]
public class Directory : IEnumerable<string>
{
    public string Name { get; set; }
    public IList<string> Files { get; set; } = [];

    public IEnumerator<string> GetEnumerator() =>
        Files.GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator() =>
        GetEnumerator();
}

snippet source | anchor

var directory = new Directory
{
    Name = "My Documents",
    Files =
    {
        "ImportantLegalDocuments.docx",
        "WiseFinancalAdvice.xlsx"
    }
};

var json = JsonConvert.SerializeObject(directory, Formatting.Indented);

Console.WriteLine(json);
// {
//   "Name": "My Documents",
//   "Files": [
//     "ImportantLegalDocuments.docx",
//     "WiseFinancalAdvice.xlsx"
//   ]
// }

snippet source | anchor