string json = @"{ 'name': 'John Smith', 'age': 45, 'isMarried': true }"; JsonTextReader reader = new JsonTextReader(new StringReader(json)); while (reader.Read()) { if (reader.Value != null) { Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value); } else { Console.WriteLine("Token: {0}", reader.TokenType); } }
JsonTextReader reader = new JsonTextReader(File.OpenText("data.json")); var serializer = new JsonSerializer(); while (reader.Read()) { if (reader.TokenType == JsonToken.StartObject) { // Deserialize the object from the JSON stream var obj = serializer.Deserialize(reader, typeof(MyObject)) as MyObject; // Do something with the deserialized object Console.WriteLine(obj.Name); } }This example shows how to use JsonTextReader and JsonSerializer to read a JSON file and deserialize JSON objects into C# objects. The code reads through each token in the JSON data and checks for the StartObject token to indicate the start of a new object. It then deserializes the object using the JsonSerializer and casts it to the appropriate C# object type. In summary, JsonTextReader is a powerful tool in the Newtonsoft.Json package for parsing and reading JSON data in C#. Its flexible and customizable approach allows for efficient and precise JSON data handling.