json object c# code example

Example 1: c# serialize json

using System.Text.Json;

//Serialize
var jsonString = JsonSerializer.Serialize(yourObject);

// Deserialize
var obj = JsonSerializer.Deserialize<YourObject>(stringValue);

Example 2: 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 3: json property C#

public class Videogame
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("release_date")]
    public DateTime ReleaseDate { get; set; }
}

Example 4: c# create a json object

dynamic ret = new JObject();

ret = new JObject(new JProperty("vendorDetails", new JObject()));

ret.vendorDetails.Add(new JProperty("vendorName", "Vendor Name"));

Tags:

Php Example