Recently, I have been dabbling in reading json data into my C# code with the intent of storing property data in the json file to be loaded at run time. For example, I'd like to make a json file for each datagrid and have each column represented as a unique as a section in the json file; something like this:
[
{
"colWidth": 1,
"rowHeight": 10,
"moreStuff": 20
},
{
"ColWidth": 2,
"rowHeight": 100,
"SecondBAID": 200
},
{
"ColWidth": 3,
"rowHeight": 1000,
"moreStuff": 2000
},
{
"ColWidth": 4,
"rowHeight": 10000,
"moreStuff": 20000,
"someArray: [true, 5, "Column notes"]
},
{
"ColWidth": 5,
"rowHeight": 100000,
"moreStuff": 200000,
"evenMoreStuff":300000
}
]
The code I am currently using to read this file and assign the data is as follows:
public static void LoadJson()
{
string json;
using (StreamReader r = new StreamReader(@"test.json"))
{
json = r.ReadToEnd();
}
dynamic array = JsonConvert.DeserializeObject(json);
var list = new List<MyClass>();
foreach (var section in array)
{
var si = new MyClass();
if (section.Whatever!= null)
{
si.Test1 = section.Whatever;
}
if (section.Whatever2!= null)
{
si.Test2 = section.Whatever2;
}
if (section.Whatever3!= null)
{
si.Test3 = section.Whatever3;
}
if (section.Whatever4!= null)
{
si.Test4 = section.Whatever4;
}
list.Add(si);
}
}
I have a few questions regarding this though...
1) Is there an easier way to filter out null values? Sometimes I want the property of a column to be the default value, and I'd rather not nest dozens of if statements if possible. Is there a way to basically say "If this property doesn't exist in the json section, just ignore it"
Presently I am just iterating through all of the possible properties, doing a simple get/set in the MyClass, and storing the variables (For this example, I use "whatevers" so I don't post hundreds of lines of code; the whatevers represent legitimate fields in the json file.
2) I am currently adding each section of the json file to a dynamic array. How can I achieve this when I want to add an array of properties to the dynamic array? I'd like to change the C# code such that if I have a nested array, it will be added to some sort of multi level list. What is the best way to do this?
I'm using this (Is it possible to have nested array json?) as a reference to nest arrays in the json.
Any advise would be awesome!