❔ Convert nested JObjects into Dictionary<string, object>
What I want is like the title, to convert any json given by the user into a
Dictionary<string, object>
Dictionary<string, object>
but keep the JSON structure. Especially if it's nested. So I figured I'd start recursively, in a sense, but I am getting stuck on the point where I attack the child tokens, since they are JToken and not JObject. And I'm not sure if they will keep working if I use
OfType<JObject>()
OfType<JObject>()
. So I could use some help converting a JObject that a user inputs to a Dictionary that keeps the JSON structure.
Here's what I've got so far:
public static Dictionary<string,object> Convert(this JObject source){ Dictionary<string,object> result = new(); foreach (KeyValuePair<string, JToken> kvp in source) { if (kvp.Value.HasValues) // aka if it has child tokens according to NewtonSoft.Json docs?? { foreach (var childToken in kvp.Value.Children().OfType<JObject>()) { childToken.Convert(); } } }}
public static Dictionary<string,object> Convert(this JObject source){ Dictionary<string,object> result = new(); foreach (KeyValuePair<string, JToken> kvp in source) { if (kvp.Value.HasValues) // aka if it has child tokens according to NewtonSoft.Json docs?? { foreach (var childToken in kvp.Value.Children().OfType<JObject>()) { childToken.Convert(); } } }}
but as you can see I'm not doing anything with childTokens at the moment because I'm not sure how to keep the original JSON structure
The reason I am trying to convert it, is because I have to do two of these mappings, and then map user-given keys of the one JSON object to the other (the values) So this part:
foreach (var prop in PropertiesToMap){ if (!dataTo.ContainsKey(prop.To) || !dataFrom.ContainsKey(prop.From)) continue; dataTo[prop.To] = dataFrom[prop.From];}
foreach (var prop in PropertiesToMap){ if (!dataTo.ContainsKey(prop.To) || !dataFrom.ContainsKey(prop.From)) continue; dataTo[prop.To] = dataFrom[prop.From];}
Please halp with my recursive function to map any json into a dictionary
And afterwards, but this is optional for me, a query question