I have read many SO posts on this subject, but either they don't deal with this level of nesting, or their answers simply haven't worked. Thank you in advance for any guidance.
I'm calling a web API that's returning a Json object, I have used the https://json2csharp.com to convert that Json to a C# class.
That all works fine, but im struggling to now convert the object to just a list of ChildComponents, meaning every childComponent in the JSON, regardless of which ChildFolder it might be in.
So at the end I just want one list, containing hundreds of ChildComponents.
public class ChildComponent
{
public int id { get; set; }
public string name { get; set; }
public string state { get; set; }
public string type { get; set; }
public string uuid { get; set; }
public List<ChildComponent> childComponents { get; set; }
public int? inboundQueueSize { get; set; }
public int? outboundQueueSize { get; set; }
public int? failedQueueSize { get; set; }
}
public class ChildFolder
{
public int id { get; set; }
public string name { get; set; }
public List<ChildFolder> childFolders { get; set; }
public List<ChildComponent> childComponents { get; set; }
public string uuid { get; set; }
}
public class Data
{
public int id { get; set; }
public string name { get; set; }
public List<ChildFolder> childFolders { get; set; }
public List<object> childComponents { get; set; }
public string uuid { get; set; }
}
public class Root
{
public Data data { get; set; }
public object error { get; set; }
}
That is the C# class, notice they can have lists of folders and components at pretty much any level.
So how can I parse all that to end up with a single list?
Currently have the json to C# in an object named js.
var response = await HttpClient.GetAsync($"{BaseUrl}api/components/status");
var content = await response.Content.ReadAsStringAsync();
var js = JsonConvert.DeserializeObject<Root>(content);
I have tried walking through js with foreach loops, but am concerned I might not be checking all the folders for components.
var folder = js.data.childFolders;
while (folder.Count > 0)
{
foreach (var childFolder in folder)
{
if (childFolder.childComponents.Count > 0)
{
foreach (var childFolderChildComponent in childFolder.childComponents)
{
Enum.TryParse<ComponentState>(childFolderChildComponent.state, out var state);
Enum.TryParse<ComponentType>(childFolderChildComponent.type, out var type);
var currentComponent = new ComponentModel
{
Id = childFolderChildComponent.id,
Name = childFolderChildComponent.name,
UUID = childFolderChildComponent.uuid,
State = state,
Type = type
};
dictComponents.TryAdd(currentComponent.Id, currentComponent);
}
}
}
}