CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public class mycustomclass
{
public string name { get; set; }
public List<string> Productlist { get; set; }
public List<string> SelectedItems { get; set; }
}
public class Program
{
public static void Main()
{
var omycustomclass = new mycustomclass
{
name = "Test",
Productlist = new[] {"Product1", "Product2", "Product3"}.ToList(),
SelectedItems = new[] {"Item1", "Item2", "Item3"}.ToList()
};
var omycustomclass2 = new mycustomclass
{
name = "Test",
Productlist = new[] {"Product4", "Product5", "Product6"}.ToList(),
SelectedItems = new[] {"Item4", "Item5", "Item6"}.ToList()
};
var foo = new Foo {Dict = new Dictionary<string, string> {{"Gee", "Whiz"}, {"Fizz", "Bang"}}};
var custom = new Dictionary<mycustomclass, List<string>>
{
{omycustomclass, new[] {"l1", "l2", "l3"}.ToList()},
{omycustomclass2, new[] {"l4", "l5", "l6"}.ToList()}
};
foo.Dict2 = custom;
var settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
ContractResolver = new DictionaryAsArrayResolver(),
Converters = new JsonConverter[] {new MyConverter()}
};
// serialize
string json = JsonConvert.SerializeObject(foo, settings);
Console.WriteLine(json);
Console.WriteLine();
// deserialize
foo = JsonConvert.DeserializeObject<Foo>(json, settings);
foreach (var kvp in foo.Dict)
{
Console.WriteLine(kvp.Key + ": " + kvp.Value);
}
}
private class Foo
{
public Dictionary<string, string> Dict { get; set; }
public IDictionary<mycustomclass, List<string>> Dict2 { get; set; }
}
}
internal class DictionaryAsArrayResolver : DefaultContractResolver
{
protected override JsonContract CreateContract(Type objectType)
{
if (objectType.GetInterfaces().Any(i => i == typeof (IDictionary) ||
(i.IsGenericType &&
i.GetGenericTypeDefinition() == typeof (IDictionary<,>))))
{
return base.CreateArrayContract(objectType);
}
return base.CreateContract(objectType);
}
}
internal class MyConverter : CustomCreationConverter<IDictionary<mycustomclass, List<String>>>
{
public override IDictionary<mycustomclass, List<String>> Create(Type objectType)
{
return new Dictionary<mycustomclass, List<String>>();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof (object) || base.CanConvert(objectType);
}
}