Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing Dynamic JSON

Tags:

json

c#

json.net

I'm receiving a JSON files that contains a list of files each with a number representing the total number of lines it contains. The file names can change over time. Does JSON.NET provide a mechanism to handle this scenario?

In the sample JSON below, I am specifically interested in items under noOfProductsByFile. The list of files is variable and I would need to consume them through some type of dynamic object.

{
  "noOfProductsByFileType" : {
    "rdi_product_stuff" : 41228,
    "rdi_product_junk" : 62519,
    "rdi_product_otherStuff" : 165023,
    "rdi_product_bobsJunk" : 1289
  },
  "startTime" : "20160907050000",
  "endTime" : "20160907052713",
  "timeTaken" : "27 minutes and 13 seconds",
  "noOfProductsBySecurityType" : {
    "AGENCIES" : 41228,
    "ASTBK" : 50991,
    "TSYCURV" : 78
  },
  "noOfProductsByFile" : {
    "rdi_product_stuff_1_of_1.json" : 41228,
    "rdi_product_junk_1_of_2.json" : 60219,
    "rdi_product_junk_2_of_2.json" : 2300,
    "rdi_product_myStuff_1_of_2.json" : 147690,
    "rdi_product_myStuff_2_of_2.json" : 17333,
    "rdi_product_test_1_of_1.json" : 1289
  },
  "noOfProducts" : 1925914
}
like image 691
user7355274 Avatar asked Feb 04 '26 00:02

user7355274


1 Answers

There are a few options to use. Here's one using the ExpandObject

dynamic dynData = JsonConvert.DeserializeObject<ExpandoObject>(jsonString, new ExpandoObjectConverter());

You can then reference the fields as you would a normal object:

dynData.noOfProductsByFileType.rdi_product_stuff

If you need to handle fields that may or may not be present, ExpandoObjects can be cast to a IDictionary and refer to fields as follows:

((IDictionary<string,object>)dynData)["noOfProductsByFileType"]

Assign to a IDictionary type and iterate through properties or test if a property exists

var dictData = (IDictionary<string,object>)dynData;
var noOfProductsByFileTypeDict = (IDictionary<string,object>)dynData.noOfProductsByFileType; // objects within objects

Test For Property

dictData.containsKey("testprop"); // test for a property - testprop

or Iterate

foreach (KeyValuePair<string, int> pair in noOfProductsByFileTypeDict) ... //iterate
like image 164
Peter Trenery Avatar answered Feb 05 '26 13:02

Peter Trenery



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!