Here is a simplified version of my JSON.
{
"Relations": [
{
"Type": "A",
"Categories": [
{ "Name": "Identity" }
]
},
{
"Type": "B",
"Categories": [
{ "Name": "Identity" },
{ "Name": "Contact Information" },
{ "Name": "Addresses" },
{ "Name": "Bank Accounts" }
]
},
{
"Type": "C",
"Categories": [
{ "Name": "Identity" },
{ "Name": "Contact Information" },
{ "Name": "ServiceFields" }
]
}
]
}
My code generates an IEnumerable (List, but I am open to suggestions if there is a more compatible option) that holds all distinct categories, meaning, it contains the following JSON:
{
"Name": "Identity"
}
{
"Name": "Contact Information"
}
{
"Name": "Addresses"
}
{
"Name": "Bank Accounts"
}
{
"Name": "ServiceFields"
}
This is the code:
void Method()
{
string jString = File.ReadAllText(@"file.json");
dynamic jObject = JsonConvert.DeserializeObject<dynamic>(jString);
var categories = new List<dynamic>();
foreach (dynamic relation in jObject.Relations)
{
foreach (dynamic category in relation.Categories)
{
if (!CollectionContainsItem(categories, category))
{
categories.Add(category);
}
}
}
// The variable in question
var result = new List<dynamic>();
foreach (var category in categories)
{
result.Add(category);
}
bool CollectionContainsItem(IEnumerable<dynamic> collection, JToken searchedItem)
{
foreach (var item in collection)
{
if (JToken.DeepEquals(item, searchedItem))
{
return true;
}
}
return false;
}
}
How to improve my code? It seems very cumbersome to me, especially the local method.
Note: I need a dynamic approach. I do not want to create C# classes for the JSON data.
Thanks!