Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create JSON string in C#

Tags:

json

c#

asp.net

People also ask

How do I create a JSON string?

married = false; //convert object to json string var string = JSON. stringify(obj); //convert string to Json Object console. log(JSON. parse(string)); // this is your requirement.

Can we convert string to JSON 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#.

What is JSON object in C?

Parsing JSON in C using microjson JavaScript Object Notation, or JSON, is a commonly used human-readable format for transmitting data objects as key-value pairs. Developed originally for server-browser communication, the use of JSON has since expanded into a universal data interchange format.

What is a string in JSON?

A JSON string contains either an array of values, or an object (an associative array of name/value pairs). An array is surrounded by square brackets, [ and ] , and contains a comma-separated list of values. An object is surrounded by curly brackets, { and } , and contains a comma-separated list of name/value pairs.


Using Newtonsoft.Json makes it really easier:

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);

Documentation: Serializing and Deserializing JSON


You could use the JavaScriptSerializer class, check this article to build an useful extension method.

Code from article:

namespace ExtensionMethods
{
    public static class JSONHelper
    {
        public static string ToJSON(this object obj)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(obj);
        }

        public static string ToJSON(this object obj, int recursionDepth)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.RecursionLimit = recursionDepth;
            return serializer.Serialize(obj);
        }
    }
}

Usage:

using ExtensionMethods;

...

List<Person> people = new List<Person>{
                   new Person{ID = 1, FirstName = "Scott", LastName = "Gurthie"},
                   new Person{ID = 2, FirstName = "Bill", LastName = "Gates"}
                   };


string jsonString = people.ToJSON();

Simlpe use of Newtonsoft.Json and Newtonsoft.Json.Linq libraries.

        //Create my object
        var myData = new
        {
            Host = @"sftp.myhost.gr",
            UserName = "my_username",
            Password = "my_password",
            SourceDir = "/export/zip/mypath/",
            FileName = "my_file.zip"
        };

        //Tranform it to Json object
        string jsonData = JsonConvert.SerializeObject(myData);

        //Print the Json object
        Console.WriteLine(jsonData);

        //Parse the json object
        JObject jsonObject = JObject.Parse(jsonData);

        //Print the parsed Json object
        Console.WriteLine((string)jsonObject["Host"]);
        Console.WriteLine((string)jsonObject["UserName"]);
        Console.WriteLine((string)jsonObject["Password"]);
        Console.WriteLine((string)jsonObject["SourceDir"]);
        Console.WriteLine((string)jsonObject["FileName"]);

This library is very good for JSON from C#

http://james.newtonking.com/pages/json-net.aspx


This code snippet uses the DataContractJsonSerializer from System.Runtime.Serialization.Json in .NET 3.5.

public static string ToJson<T>(/* this */ T value, Encoding encoding)
{
    var serializer = new DataContractJsonSerializer(typeof(T));

    using (var stream = new MemoryStream())
    {
        using (var writer = JsonReaderWriterFactory.CreateJsonWriter(stream, encoding))
        {
            serializer.WriteObject(writer, value);
        }

        return encoding.GetString(stream.ToArray());
    }
}