Search code examples
c#jsonjavascriptserializer

Deserializing JSON string with JavaScriptSerializer to return a single dynamic object instead of an array of keys and values


Consider the following JSON string in C#:

{
    "BuyerRegion":"BuyerRegion [0][27]",
    "SellerRegion":"SellerRegion [0][29]",
    "HubRegion":"HubRegion [0][31]",
    "PartNo":"TINT_MNUM [0][3]",
    "BuyerCompID":"BuyerCompId [0][28]",
    "SellerCompId":"SellerCompId [0][30]",
    "HubCompId":"HubCompId [0][32]"
}

I then tried to Deserialize the string into a dynamic object in C# using:

object obj = new JavaScriptSerializer().Deserialize<object>(s); //where s contains the JSON string

However, the returning obj is an array of key/value pairs:

enter image description here

Any idea how I can have them deserialized into one single dynamic object where I can access the properties using:

obj.BuyerRegion //returns "BuyerRegion [0][27]"

JsonConvert/NewtonSoft isn't a choice.


Solution

  • After trying several methods, I came to realize that accessing the properties is as easy as calling:

    obj["BuyerRegion"]