How to Convert String to JSON Object in C#

Muhammad Maisam Abbas Feb 02, 2024
How to Convert String to JSON Object in C#

This tutorial will discuss the methods to convert a string variable to a JSON object in C#.

Convert String to JSON Object With the JObject.Parse() Function in C#

The JObject class inside the Newtonsoft.Json package is used to represent a JSON object in C#. The Newtonsoft.Json is a high-performance JSON framework designed to be used with the .NET. The JObject class provides a method JObject.Parse() to convert a string variable containing JSON data to an instance of the JObject class. The Newtonsoft.Json package is an external package and needs to be installed before using the JObject.Parse() function. The command to install the Newtonsoft.Json package is given below.

dotnet add package Newtonsoft.Json --version 12.0.3

The following code example shows us how to convert a string variable to a JSON object with the JObject.Parse() function in C#.

using Newtonsoft.Json.Linq;
using System;
namespace fina {
  class Program {
    static void Main(string[] args) {
      string str =
          "{ \"context_name\": { \"lower_bound\": \"value\", \"upper_bound\": \"value\", \"values\": [ \"value1\", \"valueN\" ] } }";
      JObject json = JObject.Parse(str);
      foreach (var e in json) {
        Console.WriteLine(e);
      }
    }
  }
}

Output:

[context_name, {
  "lower_bound": "value",
  "upper_bound": "value",
  "values": [
    "value1",
    "valueN"
  ]
}]

In the above code, we initialized the string variable str that contains our JSON data. We used the JObject.Parse(str) function to convert the str string to the JSON object json in C#. In the end, we displayed the contents of the json object with a foreach loop.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

Related Article - Csharp String

Related Article - Csharp JSON