Using System.Text.Json in .NET Core 3 and above.
public class Order
{
public int Id { get; set; }
public string OrderNumber { get; set; }
public decimal Price { get; set; }
public DateTime OrderDate { get; set; }
var order = new Order()
{
Id = 100,
OrderNumber = "OR-100",
Balance = 39.99m,
OrderDate = DateTime.Now
};
var json = JsonSerializer.Serialize(order);
// parsing json back into order object.
var order = JsonSerializer.Deserialize<Order>(json);
The next example uses NewtonSoft's Json.Net for converting Json into a dynamic object.
If you have the relevant type for this JSON string then you can cast to
that type by providing the generic parameter to the DeserializeObject
method.
dynamic person = JsonConvert.DeserializeObject(
@"{'Name': 'Jon Smith',
'Address': { 'City': 'New York', 'State': 'NY' },
'Age': 42 }");
string name = person.Name;
string address = person.Address.City;