1 回答

TA貢獻1824條經驗 獲得超8個贊
根據您對“最佳”的定義:
在 JSON 中某處查找屬性的最短方法是將 JSON 解析為 a JObject
,然后SelectToken
與遞歸下降JsonPath 表達式一起使用:
public static string FindFirst(string json, string propertyName){ return JObject.Parse(json).SelectToken("$.." + propertyName)?.ToString();}
小提琴:https ://dotnetfiddle.net/JQxu9c
我知道用 Json.Net 做同樣事情的最快JsonTextReader
方法是使用:
public static string FindFirst(string json, string propertyName)
{
using (StringReader sr = new StringReader(json))
using (JsonReader reader = new JsonTextReader(sr))
{
while (reader.Read())
{
if (reader.TokenType == JsonToken.PropertyName &&
reader.Value.ToString() == propertyName)
{
return reader.ReadAsString();
}
}
return null;
}
}
小提琴:https ://dotnetfiddle.net/aR3qVe
- 1 回答
- 0 關注
- 99 瀏覽
添加回答
舉報