Here is a simplified version of my JSON.
{
"Relations": [
{
"Type": "A",
"Categories": [
{ "Name": "Identity" }
]
},
{
"Type": "B",
"Categories": [
{ "Name": "Identity" },
{
"Name": "Contact Information",
"Type": "Phone"
},
{ "Name": "Addresses" },
{ "Name": "Bank Accounts" }
]
},
{
"Type": "C",
"Categories": [
{ "Name": "Identity" },
{ "Name": "Contact Information" },
{ "Name": "Service Fields" }
]
}
]
}
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, when joining its values (using string.Join("\n", collection)
) it contains the following JSON:
{ "Name": "Identity" }
{
"Name": "Contact Information"
"Type": "Phone"
}
{ "Name": "Addresses" }
{ "Name": "Bank Accounts" }
{ "Name": "Contact Information" }
{ "Name": "ServiceFields" }
This is the code:
List<dynamic> Method()
{
string jString = File.ReadAllText(@"file.json");
dynamic jObject = JsonConvert.DeserializeObject<dynamic>(jString);
// The variable in questions
var categories = new List<dynamic>();
foreach (dynamic relation in jObject.Relations)
{
foreach (dynamic category in relation.Categories)
{
if (!CollectionContainsItem(categories, category))
{
categories.Add(category);
}
}
}
return categories;
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!
["Identity","Contact Information",...]
\$\endgroup\$result
) that ends up being a copy of the first (categories
)? How is this code meant to be used (since it doesn't return anything)? And how important is input validation (e.g. do you needJToken.DeepEquals
or is it safe to use(string)category.Name
for comparisons)? \$\endgroup\$result
, but after working for 10 straight hours, I believe I was just confused :). I will delete it from the question. I will edit the question to answer the other questions. Thanks for the notes! \$\endgroup\$GroupBy
part withDistinct(JToken.EqualityComparer)
should make it work as intended. \$\endgroup\$