C# - Class to Json and Json to class conversion
void Main()
{
var kanban = new KanbanBoard
{
Id = "_todo",
Title = "To Do (drag me)",
Class = "info",
Items = new List<KanbanItem>
{
new KanbanItem{
Id = "task-1",
Title = "Try drag me"
}
}
};
var ser = new DataContractJsonSerializer(typeof(KanbanBoard));
var output = string.Empty;
using (var ms = new MemoryStream())
{
ser.WriteObject(ms, kanban);
output = Encoding.UTF8.GetString(ms.ToArray());
// {"class":"info","id":"_todo","item":[{"id":"task-1","title":"Try drag me"}],"title":"To Do (drag me)"}
}
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(output)))
{
var processedKanban = (KanbanBoard)ser.ReadObject(ms);
processedKanban.Dump();
}
output.Dump();
}
[DataContract]
public class KanbanItem
{
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "title")]
public string Title { get; set; }
}
[DataContract]
public class KanbanBoard
{
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "title")]
public string Title { get; set; }
[DataMember(Name = "class")]
public string Class { get; set; }
[DataMember(Name = "item")]
public List<KanbanItem> Items { get; set; }
}