convert c# object to json code example

Example 1: object to json c#

using Newtonsoft.Json;

var jsonString = JsonConvert.SerializeObject(obj);

Example 2: string to json c#

JObject json = JObject.Parse(str);

Example 3: c# object to json string

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

Example 4: string json to class c#

var result = JsonConvert.DeserializeObject<YourClass>(jsonstring);

Example 5: c# json convert

jsonString = File.ReadAllText(fileName);
weatherForecast = JsonSerializer.Deserialize<WeatherForecast>(jsonString);

Example 6: how to convert object in string JSON c#

using System;
using System.Web.Script.Serialization;

public class MyDate
{
    public int year;
    public int month;
    public int day;
}

public class Lad
{
    public string firstName;
    public string lastName;
    public MyDate dateOfBirth;
}

class Program
{
    static void Main()
    {
        var obj = new Lad
        {
            firstName = "Markoff",
            lastName = "Chaney",
            dateOfBirth = new MyDate
            {
                year = 1901,
                month = 4,
                day = 30
            }
        };
        var json = new JavaScriptSerializer().Serialize(obj);
        Console.WriteLine(json);
    }
}