using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Collections.ObjectModel;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public string a { get; set; }
public string b { get; set; }
public string z { get; set; }
[JsonConverter(typeof(IntegerDictionaryToListConverter<MyObject>))]
public Dictionary<int, MyObject> propertyNames { get; set; }
public string otherProperty { get; set; }
public List<Datum> data { get; set; }
public class IntegerDictionaryToListConverter<T> : JsonConverter where T : class
public override bool CanConvert(Type objectType)
return typeof(Dictionary<int, T>).IsAssignableFrom(objectType);
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
if (reader.TokenType == JsonToken.Null)
var dictionary = existingValue as IDictionary<int, T> ?? (IDictionary<int, T>)serializer.ContractResolver.ResolveContract(objectType).DefaultCreator();
if (reader.TokenType == JsonToken.StartObject)
serializer.Populate(reader, dictionary);
else if (reader.TokenType == JsonToken.StartArray)
var list = serializer.Deserialize<List<T>>(reader);
for (int i = 0; i < list.Count; i++)
dictionary.Add(i, list[i]);
throw new JsonSerializationException(string.Format("Invalid token {0}", reader.TokenType));
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
throw new NotImplementedException();
public static void Test()
var root = JsonConvert.DeserializeObject<RootObject>(json);
var json2 = JsonConvert.SerializeObject(root, Formatting.Indented);
Console.WriteLine("Re-serialized {0}", root);
Console.WriteLine(json2);
""otherProperty"": ""abc""
""otherProperty"": ""bce""
public static void Main()
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
Console.WriteLine("{0} version: {1}", typeof(JsonSerializer).Assembly.GetName().Name, typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine("Failed with unhandled exception: ");
public static string GetNetCoreVersion()
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];