5

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.

dbc
  • 104,963
  • 20
  • 228
  • 340
NewbieCoder
  • 676
  • 1
  • 9
  • 32
  • You could deserialize to a `Dictionary`, then convert to an `ExpandoObject` as shown in [IDictionary to ExpandoObject extension method](https://theburningmonk.com/2011/05/idictionarystring-object-to-expandoobject-extension-method/) – dbc Jan 17 '20 at 06:25

2 Answers2

0

You can use instead of object some ModelDto and cast to it, I mean:

public class ModelDto {
  public string Key {get;set;}
  public string Value {get;set;}
}

Or you can use follwoing code to take value from dictionary by key:

string buyerRegion = dict["BuyerRegion"];

Or you can use ExpandoObject as suggested in a comments to your question.

BorHunter
  • 893
  • 3
  • 18
  • 44
0

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

obj["BuyerRegion"]
NewbieCoder
  • 676
  • 1
  • 9
  • 32