Is it possible to serialize .Net Dictionary <Key, Value> into JSON with a DataContractJsonSerializer , which has the format:
{ key0:value0, key1:value1, ... }
I use Dictionary <K, V> because there is no predefined input structure.
I'm only interested in the result of a DataContractJsonSerializer ! I already found an example of "Surrogate", but there is additional "data" in the output, and if the dictionary <K, String> is, escape is also false.
I found the solution that I need! First of all, the serializable βdictionaryβ class: (Of course, this example only works in one way, but I don't need deserialization)
[Serializable] public class MyJsonDictionary<K, V> : ISerializable { Dictionary<K, V> dict = new Dictionary<K, V>(); public MyJsonDictionary() { } protected MyJsonDictionary( SerializationInfo info, StreamingContext context ) { throw new NotImplementedException(); } public void GetObjectData( SerializationInfo info, StreamingContext context ) { foreach( K key in dict.Keys ) { info.AddValue( key.ToString(), dict[ key ] ); } } public void Add( K key, V value ) { dict.Add( key, value ); } public V this[ K index ] { set { dict[ index ] = value; } get { return dict[ index ]; } } }
Using:
public class MainClass { public static String Serialize( Object data ) { var serializer = new DataContractJsonSerializer( data.GetType() ); var ms = new MemoryStream(); serializer.WriteObject( ms, data ); return Encoding.UTF8.GetString( ms.ToArray() ); } public static void Main() { MyJsonDictionary<String, Object> result = new MyJsonDictionary<String, Object>(); result["foo"] = "bar"; result["Name"] = "John Doe"; result["Age"] = 32; MyJsonDictionary<String, Object> address = new MyJsonDictionary<String, Object>(); result["Address"] = address; address["Street"] = "30 Rockefeller Plaza"; address["City"] = "New York City"; address["State"] = "NY"; Console.WriteLine( Serialize( result ) ); Console.ReadLine(); } }
And the result:
{ "foo":"bar", "Name":"John Doe", "Age":32, "Address":{ "__type":"MyJsonDictionaryOfstringanyType:#Json_Dictionary_Test", "Street":"30 Rockefeller Plaza", "City":"New York City", "State":"NY" } }