you can use the JsonConvert class provided by the Newtonsoft.Json package. Here's an example:
xxxxxxxxxx
using Newtonsoft.Json;
string jsonString = "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}";
// Convert the string to a JSON object
JObject json = JObject.Parse(jsonString);
// Or, you can also use the JsonConvert class to deserialize the string into a JSON object
JObject json = JsonConvert.DeserializeObject<JObject>(jsonString);
//the JObject class represents a JSON object, and Parse and DeserializeObject methods
//are used to convert the string to a JSON object. Once you have a JSON object,
//you can access its properties using the [] operator:
//c#
string name = (string)json["name"];
int age = (int)json["age"];
string city = (string)json["city"];
xxxxxxxxxx
using System;
using System.Text.Json;
public class Program
{
public static void Main()
{
string jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
// Convert string to JsonDocument
JsonDocument jsonDocument = JsonDocument.Parse(jsonString);
// Convert JsonDocument to string (formatted)
string jsonFormattedString = jsonDocument.RootElement.ToString();
Console.WriteLine(jsonFormattedString);
// Convert JsonDocument to string (minified)
string jsonMinifiedString = jsonDocument.RootElement.ToString();
Console.WriteLine(jsonMinifiedString);
}
}
xxxxxxxxxx
using System;
using System.Text.Json;
// Define a class representing the structure of the JSON object
public class MyObject
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Program
{
public static void Main()
{
string jsonString = "{\"Id\": 1, \"Name\": \"John\"}";
// Deserialize the JSON string to an object of MyObject
MyObject obj = JsonSerializer.Deserialize<MyObject>(jsonString);
// Access and use the object properties
Console.WriteLine("Id: " + obj.Id);
Console.WriteLine("Name: " + obj.Name);
}
}
xxxxxxxxxx
using System;
using Newtonsoft.Json;
// Define a class to convert to JSON
public class MyClass
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
// Create an instance of MyClass
MyClass obj = new MyClass
{
Name = "John Doe",
Age = 30
};
// Convert object to JSON string
string json = JsonConvert.SerializeObject(obj);
Console.WriteLine(json);
}
}