BlackMorokei BlackMorokei - 20 days ago 9
C# Question

How to read JSON file and select specific values C# [Done]

I'm a beginner in development so please don't judge.
I need to read many (like 74) JSON files and all of them have other values.
How can I read the JSON files dynamicly and can select specific values?

Currently I use Newtonsoft Json, but I don't know how I can get specific values.
So as a sample this is one of the JSON file.

{
"value": [
{
"resourceRef": "/accessControlLists/abc123",
"resourceId": "abc123",
"resourceMetadata": {
"resourceName": "SCVMM Default ACL"
},
"etag": "W/\"ea02b098-bcd1-406a-abff-ab380011d510\"",
"instanceId": "e123f536-ffc1-429e-b67e-50627b1613c8",
"properties": {
"provisioningState": "Succeeded",
"aclRules": [
{
"resourceRef": "/accessControlLists/abc123/aclRules/def456",
"resourceId": "def456",
"etag": "W/\"ea02b098-bcd1-406a-abff-ab380011d510\"",
"instanceId": "e3467412-e9c7-48a0-9d45-bdaedbe72d2d",
"properties": {
"provisioningState": "Succeeded",
"protocol": "All",
"sourcePortRange": "*",
"destinationPortRange": "*",
"action": "Allow",
"sourceAddressPrefix": "*",
"destinationAddressPrefix": "*",
"priority": "65000",
"description": "SCVMM Default Rule - Allow All",
"type": "Inbound",
"logging": "Enabled"
}
}
],
"ipConfigurations": [],
"subnets": []
}
}
],
"nextLink": ""
}


The second file is like this.

{
"resourceRef": "/virtualNetworkManager/",
"instanceId": "00000000-0000-0000-0000-000000000000",
"properties": {
"provisioningState": "Succeeded",
"distributedRouterState": "Enabled",
"networkVirtualizationProtocol": "VXLAN"
}
}


So how can I read as a sample the description of the first file?
And how can I do it dynamicly?

Thanks for help!

Edit:
dynamic
with
JsonConvert
worked for me.

string path = string.Empty;
Console.Write("Please enter json file path: ");
path = Console.ReadLine();

dynamic obj = JObject.Parse(File.ReadAllText(path));
for (int i = 0; i < obj.value.Count; i++)
{
for (int j = 0; j < obj.value[i].properties.aclRules.Count; j++)
{
Console.WriteLine(obj.value[i].properties.aclRules[j].properties.description);
}
}

Jim Jim
Answer

How can I read the JSON files dynamically and can select specific values? So how can I read as a sample the description of the first file? And how can I do it dynamically

With the dynamic functionality :

dynamic obj = JsonConvert.DeserializeObject(json);

var description = obj.value[0].properties.aclRules[0].properties.description;