Serializing a Dictionary <> of an Object Using a DataContractJsonSerializer

I have the following Dictionary<> object:

 Dictionary<String, object> parameters = new Dictionary<string, object>(); parameters.Add("username", "mike"); parameters.Add("password", "secret"); parameters.Add("persist", false); 

When I serialize it:

 using (MemoryStream stream = new MemoryStream()) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(parameters.GetType()); serializer.WriteObject(stream, parameters); byte[] bytes = stream.ToArray(); string json = Encoding.UTF8.GetString(bytes, 0, bytes.Length); return json; } 

I get the following:

 "[{\"Key\":\"username\",\"Value\":\"mike\"},{\"Key\":\"password\",\"Value\":\"secret\"},{\"Key\":\"persist\",\"Value\":false}]" 

What I want to get is a map of cards with a key / value, for example:

 "{\"username\":\"mike\", \"password\":\"secret\", \"persist\": false}" 

I tried setting UseSimpleDictionaryFormat to true, but this property has no effect, and its intended use is not documented anywhere else I can find.

I cannot use a custom class as parameter / parameter value pairs are not known at compile time.

I also cannot use a third-party library such as JSon.NET. I am using Silverlight and the Windows Phone 8 production environment.

+4
source share
2 answers

Try serializing this

 var parameters = new { username = "mike", password = "secret", persist = false } 
+2
source

After adding System.Json as a reference, use this helper class to create JSON properties:

 public static class JsonHelper { public static KeyValuePair<string, JsonValue> CreateProperty(string name, dynamic value) { return new KeyValuePair<string, JsonValue>(name, new JsonPrimitive(value)); } } 

The following LINQ query will dynamically return JSON properties as JsonArray using the Helper class.

 var result = from item in parameters select new JsonObject(JsonHelper.CreateProperty(item.Key, item.Value)); string json = (new JsonArray(result)).ToString(); 

Result:

 [{\"username\":\"mike\"},{\"password\":\"secret\"},{\"persist\":false}] 
+2
source

All Articles