Search code examples
.netjsontokenjson-deserialization

json.net get all json tokens and readout specific properties


I have the following json file:

{
  "GuiElement0": {
    "gHeight": "50",
    "gID": "0",
    "gY": "80"
  },
  "GuiElement1": {
    "gFile": "",
    "gID": "0",
    "gStyle": "2",
    "gX": "130",
    "gY": "240"
  },
  "GuiElement2": {
    "gThickness": "1",
    "gID": "0",
    "gStyle": "3",
    "gX": "150",
    "gY": "20"
  }
}

Now i would like to iterate through the single elements like this:

JObject json = JObject.Parse(file.ReadToEnd());
foreach (JToken token in json.Children())
{
    if(JObject.Parse(token.ToString()).GetValue("gID").ToString() == "0" )
    {
        MessageBox.Show(JObject.Parse(token.ToString()).Property("gID").ToString());
    }
}

Unfortunately this does not work as expected. My goal is to readout the gID for each token and then to process each of the elements seperatley.

If i have got the ID, then i will dezerialize the json

"gThickness": "1",
"gID": "0",
"gStyle": "3",
"gX": "150",
"gY": "20"

like this:

(GuiElement)JsonConvert.DeserializeObject<GuiBar>(token.ToString());

It would be great if someone could point me to my mistake. Thanks!


Solution

  • I found the solution:

    foreach (JProperty prop in json.Children())
    {
    
        JToken value = prop.Value;
        if(value.Type == JTokenType.Object)
        {
            MessageBox.Show(((JObject)value).GetValue("gID").ToString());
        }
    
    }