📜  JSONStringify c# - Javascript (1)

📅  最后修改于: 2023-12-03 14:43:35.085000             🧑  作者: Mango

JSONStringify C# - Javascript

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.

JSONStringify in 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)
  • object – It is the JavaScript object that you want to convert to JSON string.
  • replacer – It is an optional parameter. It can be a function or an array that specifies which properties of the object are to be included in the JSON string.
  • space – It is an optional parameter that specifies the number of spaces for indentation.

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"}
JSONStringify in C#

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"}
Conclusion

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.