C # JSON Serializing a dictionary in {key: value, ...} instead of {key: key, value: value, ...}

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" } } 
+46
json dictionary c # serialization
Feb 01 2018-11-11T00:
source share
4 answers

Json.NET does it ...

 Dictionary<string, string> values = new Dictionary<string, string>(); values.Add("key1", "value1"); values.Add("key2", "value2"); string json = JsonConvert.SerializeObject(values); // { // "key1": "value1", // "key2": "value2" // } 

Additional Examples: Serializing Collections Using Json.NET

+33
Jan 30 '15 at 10:50
source share

use the UseSimpleDictionaryFormat property in the DataContractJsonSerializer and set it to true .

Is this the task :)

+9
Jul 21 '15 at 7:23
source share

I use out of the box MVC4 with this code (note the two parameters inside ToDictionary )

  var result = new JsonResult() { Data = new { partials = GetPartials(data.Partials).ToDictionary(x => x.Key, y=> y.Value) } }; 

I get the expected:

 {"partials":{"cartSummary":"\u003cb\u003eCART SUMMARY\u003c/b\u003e"}} 



Important : WebAPI in MVC4 uses JSON.NET serialization out of the box, but the result of working with the JsonResult website JsonResult not work. Therefore, I recommend using custom ActionResult to force JSON.NET serialization. You can also get beautiful formatting

Here's a simple actionresult JsonNetResult

http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx

When serializing the date, you will see the difference (and you can make sure that you are using the correct one):

Microsoft way:

  {"wireTime":"\/Date(1355627201572)\/"} 

JSON.NET Method:

  {"wireTime":"2012-12-15T19:07:03.5247384-08:00"} 
+4
Dec 16 '12 at 2:40
source share

Unfortunately, this is not possible in the latest version of DataContractJsonSerializer. See: http://connect.microsoft.com/VisualStudio/feedback/details/558686/datacontractjsonserializer-should-serialize-dictionary-kv-as-a-json-associative-array

It is currently proposed to use the JavaScriptSerializer as described above.

Good luck

+2
Feb 02 '12 at 23:24
source share



All Articles