c# string 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# parse json

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);
//{
//  "Name": "Apple",
//  "Expiry": "2008-12-28T00:00:00",
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);

Example 4: c# object to json string

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

Example 5: string json to class c#

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

Example 6: c# json convert

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

Tags:

Go Example