How to Convert string to JSON in C#

By FoxLearn 11/19/2024 7:06:39 AM   88
You can convert a string to a JSON object in C# using the `JsonSerializer.Deserialize` method from the `System.Text.Json` namespace.

Make sure to import the `System.Text.Json` namespace in your application before calling the `JsonSerializer.Deserialize` method.

For example:

// Convert string to json in c#
string jsonString = "{\"name\":\"Lucy\", \"age\":30, \"city\":\"New York\"}";

// Deserialize into a dynamic object
var jsonObject = JsonConvert.DeserializeObject(jsonString);

This code deserializes a JSON string into a object, allowing you to access its properties directly.

// Access the values
Console.WriteLine(jsonObject.name);  // Output: Lucy
Console.WriteLine(jsonObject.age);   // Output: 30
Console.WriteLine(jsonObject.city);  // Output: New York

You can also deserialize into a specific class or a strongly-typed object, like this:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string City { get; set; }
}
// Deserialize into a specific class
var person = JsonConvert.DeserializeObject<Person>(jsonString);
Console.WriteLine(person.Name);  // Output: Lucy
Console.WriteLine(person.Age);   // Output: 30
Console.WriteLine(person.City);  // Output: New York

If you are using .NET Core or a later version of .NET, you can use the built-in System.Text.Json library, which is part of the framework and does not require additional packages.

For example:

// c# convert string to json, deserialize into a dynamic object
var jsonObject = JsonSerializer.Deserialize<JsonElement>(jsonString);

You can also deserialize into a strongly-typed object using System.Text.Json:

For example:

// convert string to json c#, deserialize into a specific class
Person person = JsonSerializer.Deserialize<Person>(jsonString);

If you're working on a project that is already using Newtonsoft.Json or requires specific advanced features, stick with Json.NET.

If you want to keep things simple and are working with .NET Core or later, System.Text.Json may be the better choice.