What is the JSON.NET equivalent of XML's XPath, SelectNodes, SelectSingleNode?

前端 未结 2 1833
时光取名叫无心
时光取名叫无心 2020-11-27 19:16

At present, the structure of my code uses XmlDocument to load Xml data and then SelectNodes to iterate through a list of repeating items.

F

2条回答
  •  醉梦人生
    2020-11-27 20:05

    Json.NET has SelectToken. It uses a syntax similar to DataBinder.Eval to get JSON via a string expression:

    JObject o = JObject.Parse("{'People':[{'Name':'Jeff'},{'Name':'Joe'}]}");
    
    // get name token of first person and convert to a string
    string name = (string)o.SelectToken("People[0].Name");
    

    Or if you wanted to select multiple values:

    JObject o = JObject.Parse("{'People':[{'Name':'Jeff','Roles':['Manager', 'Admin']}]}");
    
    // get role array token of first person and convert to a list of strings
    IList names = (string)o.SelectToken("People[0].Roles").Select(t => (string)t).ToList();
    

    Documentation: Querying JSON with SelectToken

提交回复
热议问题