How to Convert Strings to JSON Objects in C#?
In C#, the Newtonsoft.Json
library (also known as Json.NET) provides robust support for JSON serialization and deserialization. To convert a JSON string into a JSON object, you can use the JObject.Parse()
method provided by Json.NET
. This method parses the JSON string and returns a JObject
representing the JSON data.
using Newtonsoft.Json.Linq;
using System;
class Program
{
static void Main(string[] args)
{
string jsonString = "{\"name\":\"Peter\",\"age\":35,\"city\":\"Chennai\"}";
// Convert JSON string to JObject
JObject jsonObject = JObject.Parse(jsonString);
// Accessing values from the JObject
string name = (string)jsonObject["name"];
int age = (int)jsonObject["age"];
string city = (string)jsonObject["city"];
// Output
Console.WriteLine("Name: " + name);
Console.WriteLine("Age: " + age);
Console.WriteLine("City: " + city);
}
}
In this program, we have defined a JSON string representing a simple object with properties like "name," "age," and "city." We used the JObject.Parse()
method to convert this string into a JObject
. Once we have the JObject
, we have easily accessed individual properties using indexing and cast them to their appropriate data types. If you need any C# project assistance, feel free to reach out.
Output:
Name: Peter
Age: 35
City: Chennai
Comments (0)