通过JObject循环获取属性名称

时间:2017-06-01 17:30:23

标签: c# json foreach children

正如标题中描述的那样,我试图循环通过一个JObject来获取内部键的所有名称,但是你可以看到这是在子键“Bayonet”下指定的。虽然这样工作正常,但我需要一种更通用的方法,因为“刺刀”子键不会总是存在。以下是我的一些尝试:

工作解决方案但未通用化:

foreach (JProperty condition in SkinData[Skin]["Bayonet"])
{
     conditionlines.Add(condition.Name);
}

失败无法将JObject转换为JProperty错误:

foreach (JProperty condition in SkinData[Skin].First)
{
    conditionlines.Add(condition.Name);
}

没有名称字符串错误:

foreach (JProperty condition in SkinData[Skin][0])
{
    conditionlines.Add(condition.Name);
}

JSON:

{  
   "Scorched":{  
      "Bayonet":{  
         "FN":"51",
         "MW":"32",
         "FT":"25",
         "WW":"26",
         "BS":"26"
      },
      "Bowie Knife":{  
         "MW":"25",
         "FT":"20",
         "WW":"21",
         "FN":"41",
         "BS":"20"
      },
      "Butterfly Knife":{  
         "FN":"50",
         "MW":"36",
         "FT":"29",
         "WW":"28",
         "BS":"29"
      },
      "Falchion Knife":{  
         "FN":"31",
         "MW":"20",
         "FT":"17",
         "WW":"17",
         "BS":"17"
      },
      "Flip Knife":{  
         "FN":"0",
         "MW":"24",
         "FT":"20",
         "WW":"20",
         "BS":"20"
      },
      "Gut Knife":{  
         "FN":"0",
         "MW":"19",
         "FT":"17",
         "WW":"18",
         "BS":"17"
      },
      "Huntsman Knife":{  
         "FN":"48",
         "MW":"27",
         "FT":"21",
         "WW":"21",
         "BS":"20"
      },
      "Karambit":{  
         "FN":"87",
         "MW":"55",
         "FT":"43",
         "WW":"42",
         "BS":"41"
      },
      "M9 Bayonet":{  
         "FN":"54",
         "MW":"38",
         "FT":"30",
         "WW":"30",
         "BS":"30"
      },
      "Shadow Daggers":{  
         "FN":"29",
         "MW":"20",
         "FT":"17",
         "WW":"17",
         "BS":"17"
      }
   }
}

1 个答案:

答案 0 :(得分:0)

你可以这样做:

foreach (var condition in ((JContainer)SkinData[Skin]).Descendants().OfType<JObject>().Take(1).Properties())
{
     conditionlines.Add(condition.Name);
}       

这会找到Skin指定的JObject类型var pattern = @"\s\[.*\]"; var regex = new Regex(pattern); var result = regex.Replace(query, ""); 的第一个descendant(如果有),然后遍历其properties

示例fiddle