Mittwoch, 18. März 2020

json - newtowsoft - JArray - SelectToken

how to fill JArray and select all and specific items? 

private Newtonsoft.Json.Linq.JArray UFOS = new jsonlib.Linq.JArray();

dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(myUFOjsonSourceString);

var list = json.list; // List of UFO items - 'list' is the root element of the source JSON structure

foreach (var item in list)
{
..
UFOS.Add(item);
...
}

IEnumerable<jsonlib.Linq.JToken> allUFOS= UFOS.SelectToken("$"); // okay, all UFOs

IEnumerable<jsonlib.Linq.JToken> oneUFO = UFOS.SelectToken("$[?(@.Pilot=='E.T.')]"); // okay, if each item of UFO would contain the property 'Pilot', select the one where Pilot=E.T. (you know, this small odd alien who wants to get home again)

Sample II:

Parse XML using Newtonsoft.Json

<root>
  <light>
    <color>red</color>
    <intensity>bright</intensity>
  </light>
  <light>
    <color>green</color>
    <intensity>light</intensity>
  </light>
</root>

XDocument doc = XDocument.Parse(mySampleXmlString); //or XDocument.Load(path)
string jsonText = JsonConvert.SerializeXNode(doc);
dynamic pseudoXml = JsonConvert.DeserializeObject(jsonText);
Newtonsoft.Json.Linq.JArray lights = (Newtonsoft.Json.Linq.JArray)pseudoXml["root"]["light"];
foreach (var light in lights)
{
    string color = (string)light.color;
    string intensity = (string)light.intensity;
}

Keine Kommentare:

Kommentar posten