How can I parse JSON with C#?

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;

Jack Poorte
Jack Poorte
Last updated on Sep 30, 2023

Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Cookies       Do Not Sell       Licensing      
Made with    in Austin, Texas.  - vsn 44.0.0
© Data & Object Factory, LLC.