Learn how to get data from a JSON object in .NET C# using the Newtonsoft.Json library. Follow this simple step-by-step guide to access the values of properties in a JSON object.
To get data from a JSON object in C#, you can use the Newtonsoft.Json
library. Here’s an example of how to do it:
- Deserialize the JSON string into a C# object using the
JsonConvert.DeserializeObject
method:
string jsonString = "{\"name\":\"John Smith\",\"age\":30}";
dynamic jsonObj = JsonConvert.DeserializeObject(jsonString);
- Access the values of properties in the JSON object by using the dot notation:
string name = jsonObj.name; // "John Smith"
int age = jsonObj.age; // 30
Alternatively, you can use the JObject
class to access the properties:
JObject jsonObj = JObject.Parse(jsonString);
string name = (string)jsonObj["name"]; // "John Smith"
int age = (int)jsonObj["age"]; // 30
Note that you’ll need to include the Newtonsoft.Json
namespace in your C# file for these examples to work.