Reputation: 144
I've got JSON children/tree representation like this:
{
"someObj":
{
"test": 10
},
"children":
[
{
"someObj":
{
"test": 11
},
"children":
[
{
"someObj":
{
"test": 12,
"children": null
}
}
]
},
{
"someObj":
{
"test": 12
},
"children":
[
{
"someObj":
{
"test": 13,
"children": null
}
}
]
}
]
}
I'm deserializing it to C# class representation:
public class Example
{
public Dictionary<string, object> SomeObj { get; set; }
public IList<Example> Children { get; set; }
//Extended with Parent prop
public Example Parent { get; set; }
}
What I want to do is extend my model class Example
with Parent
property. Parent
should contain all information about 'previous'child object - example: "someObj: { "test": 11 }
knows that its parent is "someObj": { "test": 10 }
Should I write some JsonConverter to achieve this? Or maybe do some method after deserialization which gonna loop after all nested (children) objects and creates their parents?
Upvotes: 0
Views: 1147
Reputation: 841
It is convenient to use json conversion event OnDeserialized - your post-process will start automatically. Something like this:
public class Example
{
public Dictionary<string, object> SomeObj { get; set; }
public IList<Example> Children { get; set; }
//Extended with Parent prop
public Example Parent { get; set; }
[OnDeserialized]
protected void OnDeserializedMethod(StreamingContext context)
{
RegisterParentRecursive(this);
}
public void RegisterParentRecursive(Example parent)
{
foreach (var child in parent.Children)
{
child.Parent = parent;
RegisterParentRecursive(child);
}
}
}
Upvotes: 0
Reputation: 13783
As far as I'm aware, it's not easy to set up your JSON conversion to do this. You can roll your own converter to do it for you, but it may bring additional complexities to the tables that make it not worth the effort required.
Alternatively, you could just post-process the structure. Since you already have the hierarchy defined (through Children
), it's not that hard to now also reference the parent by traversing the hierarchy.
This can be done with a fairly simple recursive method:
public void RegisterParentRecursive(Example parent)
{
foreach(var child in parent.Children)
{
child.Parent = parent;
RegisterParentRecursive(child);
}
}
And you simply call it on the top level parent:
Example topLevelParent = ParseMyJSON();
RegisterParentRecursive(topLevelParent);
As this is an in-memory process, it will not be a performance hog.
Also, for sufficiently large structures that make traversal less than trivial, I expect you're going to run into other issues first (JSON string size, deserialization performance, ...), thus not really making the post-processing itself the biggest bottleneck.
Upvotes: 3