How can I deserialize JSON with C#?
c#, deserialization, dictionary, json
Solution
I am assuming you are not using Json.NET (Newtonsoft.Json NuGet package). If this the case, then you should try it.
It has the following features:
- LINQ to JSON
- The JsonSerializer for quickly converting your .NET objects to JSON and back again
- Json.NET can optionally produce well formatted, indented JSON for debugging or display
- Attributes like `JsonIgnore` and `JsonProperty` can be added to a class to customize how a class is serialized
- Ability to convert JSON to and from XML
- Supports multiple platforms: .NET, Silverlight and the Compact Framework
Look at the example below. In this example, `JsonConvert` class is used to convert an object to and from JSON. It has two static methods for this purpose. They are `SerializeObject(Object obj)` and `DeserializeObject<T>(String json)`:
using Newtonsoft.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);
Problem
I have the following code: ``` var user = (Dictionary<string, object>)serializer.DeserializeObject(responsecontent); ``` The input in `responsecontent` is JSON, but it is not properly deserialized into an object. How should I properly deserialize it?
Related problems
- How to write a JSON file in C#?
- Deserialize JSON into C# dynamic object?
- Attempt by method 'System.Web.Helpers.Json..cctor()' to access method 'System.Web.Helpers.Json.CreateSerializer()' failed
- Anything new in .Net 4.5 to process better JSON?
- Equivalent of JObject in System.Text.Json
- Where can I find System.Web.Helpers, System.Web.WebPages, and System.Web.Razor?