📅  最后修改于: 2023-12-03 14:43:35.085000             🧑  作者: Mango
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy to read and write. It is widely used in web applications for sending data from server to web browser. JSON can be easily converted to object and vice versa in JavaScript. However, in C#, JSON object is not directly supported. In this article, we will discuss JSONStringify in C# and JavaScript.
JSON.stringify() method is used to convert a JavaScript object to a JSON string. The syntax for JSON.stringify() method is as follows:
JSON.stringify(object, replacer, space)
Here is an example of using JSON.stringify() method:
const obj = { name: 'John', age: 30, city: 'New York' };
const jsonString = JSON.stringify(obj);
console.log(jsonString);
Output:
{"name":"John","age":30,"city":"New York"}
To be able to convert C# object to JSON string, we need to use external libraries like Newtonsoft.Json or System.Text.Json. Here is an example of using Newtonsoft.Json:
using Newtonsoft.Json;
class Program
{
static void Main(string[] args)
{
var obj = new { name = "John", age = 30, city = "New York" };
var jsonString = JsonConvert.SerializeObject(obj);
Console.WriteLine(jsonString);
}
}
Output:
{"name":"John","age":30,"city":"New York"}
In this article, we have discussed JSONStringify in C# and JavaScript. We have seen how JSON.stringify() method can be used in JavaScript to convert a JavaScript object to a JSON string. We have also seen how external libraries like Newtonsoft.Json can be used in C# to achieve the same result.