我有一个像这样的json块:
{ "ADDRESS_MAP":{ "ADDRESS_LOCATION":{ "type":"separator", "name":"Address", "value":"", "FieldID":40 }, "LOCATION":{ "type":"locations", "name":"Location", "keyword":{ "1":"LOCATION1" }, "value":{ "1":"United States" }, "FieldID":41 }, "FLOOR_NUMBER":{ "type":"number", "name":"Floor Number", "value":"0", "FieldID":55 }, "self":{ "id":"2", "name":"Address Map" } } }
我如何获取此令牌包含的所有关键项目。例如,从上面的代码中,我希望具有“ ADRESS_LOCATION”,“ LOCATION”,“ FLOOR_NUMBER”和“ self”。
您可以将JToken转换为JObject,然后使用Properties()方法获取对象属性的列表。从那里,您可以轻松获得名称。
JToken
JObject
Properties()
像这样:
string json = @"{ ""ADDRESS_MAP"":{ ""ADDRESS_LOCATION"":{ ""type"":""separator"", ""name"":""Address"", ""value"":"""", ""FieldID"":40 }, ""LOCATION"":{ ""type"":""locations"", ""name"":""Location"", ""keyword"":{ ""1"":""LOCATION1"" }, ""value"":{ ""1"":""United States"" }, ""FieldID"":41 }, ""FLOOR_NUMBER"":{ ""type"":""number"", ""name"":""Floor Number"", ""value"":""0"", ""FieldID"":55 }, ""self"":{ ""id"":""2"", ""name"":""Address Map"" } } }"; JToken outer = JToken.Parse(json); JObject inner = outer["ADDRESS_MAP"].Value<JObject>(); List<string> keys = inner.Properties().Select(p => p.Name).ToList(); foreach (string k in keys) { Console.WriteLine(k); }
输出:
ADDRESS_LOCATION LOCATION FLOOR_NUMBER self