json to C# string code example

Example 1: c# string to memorystream

public static MemoryStream GenerateStreamFromString(string value)
{
    return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
}

Example 2: string to enum c#

Enum.TryParse("Active", out StatusEnum myStatus);

Example 3: object to json c#

using Newtonsoft.Json;

var jsonString = JsonConvert.SerializeObject(obj);

Example 4: create json string c#

//Create my object
        var my_jsondata = 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 json_data = JsonConvert.SerializeObject(my_jsondata);

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

        //Parse the json object
        JObject json_object = JObject.Parse(json_data);

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

Example 5: string to json c#

JObject json = JObject.Parse(str);

Example 6: c# object to json string

Newtonsoft.Json.JsonConvert.SerializeObject(new {foo = "bar"})