Created
July 3, 2012 20:09
-
-
Save rally25rs/3042650 to your computer and use it in GitHub Desktop.
Serialize an ExpandoObject to a JSON string by wrapping it in a DynamicJsonObject
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// By default, Json.Encode will turn an ExpandoObject into an array of items, | |
// because internally an ExpandoObject extends IEnumerable<KeyValuePair<string, object>>. | |
// You can turn it into a non-list JSON string by first wrapping it in a DynamicJsonObject. | |
[TestMethod] | |
public void JsonEncodeAnExpandoObjectByWrappingItInADynamicJsonObject() | |
{ | |
dynamic expando = new ExpandoObject(); | |
expando.Value = 10; | |
expando.Product = "Apples"; | |
var expandoResult = System.Web.Helpers.Json.Encode(expando); | |
var dictionaryResult = System.Web.Helpers.Json.Encode(new DynamicJsonObject(expando)); | |
Assert.AreEqual("{\"Value\":10,\"Product\":\"Apples\"}", expandoResult); // FAILS (encodes as an array instead) | |
Assert.AreEqual("{\"Value\":10,\"Product\":\"Apples\"}", dictionaryResult); // PASSES | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment