JsonObjectAttribute force object serialization |
This sample uses JsonObjectAttribute to serialize a class that implements IEnumerableT 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 Directory() { Files = new List<string>(); } public IEnumerator<string> GetEnumerator() { return Files.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }
Directory directory = new Directory { Name = "My Documents", Files = { "ImportantLegalDocuments.docx", "WiseFinancalAdvice.xlsx" } }; string json = JsonConvert.SerializeObject(directory, Formatting.Indented); Console.WriteLine(json); // { // "Name": "My Documents", // "Files": [ // "ImportantLegalDocuments.docx", // "WiseFinancalAdvice.xlsx" // ] // }