using Newtonsoft.Json; string json = "{ \"name\": \"John\", \"age\": 30 }"; JsonReader reader = new JsonTextReader(new StringReader(json)); while (reader.Read()) { if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == "name") { reader.Read(); Console.WriteLine("Name: " + (string)reader.Value); } else if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == "age") { reader.Read(); Console.WriteLine("Age: " + (int)reader.Value); } }
using Newtonsoft.Json; string file = "person.json"; using (StreamReader fileReader = File.OpenText(file)) { JsonReader reader = new JsonTextReader(fileReader); while (reader.Read()) { if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == "name") { reader.Read(); Console.WriteLine("Name: " + (string)reader.Value); } else if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == "age") { reader.Read(); Console.WriteLine("Age: " + (int)reader.Value); } } }In this example, we read and parse a JSON file with a similar structure as the previous example. We use a StreamReader to read the file and create a JsonTextReader object to parse the JSON data. Both examples use the Newtonsoft.Json package library in C#.