using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.ComponentModel;
using System.Globalization;
using System.Collections.Specialized;
using System.Web.Routing;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Formatters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public class CardListViewModel
public virtual Guid Id { get; set; }
public virtual IEnumerable<Card> CardList { get; set; }
public virtual Guid Id { get; set; }
public virtual string IndexName { get; set; }
public virtual Image CardImage { get; set; }
public virtual string Src { get; set; }
public class CardListConverter : JsonConverter
public override bool CanConvert(Type objectType)
return typeof(IEnumerable<Card>).IsAssignableFrom(objectType);
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
if (reader.TokenType == JsonToken.Null)
var list = existingValue as ICollection<Card> ?? new List<Card>();
var obj = JObject.Load(reader);
foreach (var property in obj.Properties())
list.Add(new Card { IndexName = property.Name, CardImage = new Image { Src = (string)property.Value } });
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
var collection = (IEnumerable<Card>)value;
writer.WriteStartObject();
foreach (var item in collection)
writer.WritePropertyName(item.IndexName);
writer.WriteValue(item.CardImage == null ? null : item.CardImage.Src);
public static void Test()
var CardListViewModel = new CardListViewModel
Id = new Guid("c2a7cc0f-0e6b-40a0-9020-aeba436265d4"),
CardList = new List<Card>()
new Card {Id = new Guid(5678, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), IndexName = "Visa", CardImage = new Image { Src = "Visa.png" }},
new Card {Id = new Guid(5555, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), IndexName = "MasterCard", CardImage = new Image { Src = "MasterCard.png" }}
var settings = new JsonSerializerSettings
Converters = { new CardListConverter() },
var json = JsonConvert.SerializeObject(CardListViewModel, Formatting.Indented, settings);
Console.WriteLine("Serialized {0}:", CardListViewModel);
var model2 = JsonConvert.DeserializeObject<CardListViewModel>(json, settings);
var json2 = JsonConvert.SerializeObject(model2, Formatting.Indented, settings);
Console.WriteLine("Deserialized and re-serialized {0}:", model2);
Console.WriteLine(json2);
public static void Main()
Console.WriteLine("Environment version: " + Environment.Version);
Console.WriteLine("Json.NET version: " + typeof(JsonSerializer).Assembly.FullName);