0

I have a long tree json document, here is the part of it

"childs": [
    {
      "id": "id1",
      "name": "name1",
      "childs": []
    },
    {
      "id": "id2",
      "name": "name21",
      "childs": [
        {
          "id": "id3",
          "name": "name123124",
          "childs": [
            {
              "id": "id4",
              "name": "namewe1231",
              "childs": [
                {
                  "id": "id5",
                  "name": "name123123",
                  "childs": [
                    {
                      "id": "id5",

`

i need to save all id from this document for local storage like: id1 id2 id3 id4 etc... is it even possible? JObject and dynamic variable didnt help me.

heres code i've been trying to compile but it returned me just first id from tree `

string source = File.ReadAllText(jsonModelPath);
            dynamic data = JObject.Parse(source);
            File.WriteAllText(path, data.id);

`

  • I think one of the ideas is to flatten your object, and then select the properties with ids in it. See this post for some inspiration, https://stackoverflow.com/questions/32782937/generically-flatten-json-using-c-sharp – Charles Han Nov 15 '22 at 07:34
  • @CharlesHan yes, this post helped me to solve my problem, thank you very much – Alexey Savelyev Nov 15 '22 at 08:01
  • @AlexeySavelyev please post the final sample and close the post with your answer. – CthenB Nov 15 '22 at 09:37

1 Answers1

0

you can try something like this

string[] ids = JObject.Parse(json)
        .Descendants()
        .OfType<JProperty>()
        .Where(a => a.Name == "id")
        .Select(a => a.Value.ToString())
        .ToArray();

or you can put all ids in one line

 string strIds = string.Join(" ",ids);

or each id in the new line

 string strIds = string.Join("\n",ids);

and save

File.WriteAllText(path, strIds);
Serge
  • 40,935
  • 4
  • 18
  • 45