How can I parse JSON with C#?
Solution 1:
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
andJsonProperty
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)
:
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);
Solution 2:
As was answered here - Deserialize JSON into C# dynamic object?
It's pretty simple using Json.NET:
dynamic stuff = JsonConvert.DeserializeObject("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");
string name = stuff.Name;
string address = stuff.Address.City;
Or using Newtonsoft.Json.Linq :
dynamic stuff = JObject.Parse("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");
string name = stuff.Name;
string address = stuff.Address.City;
Solution 3:
Here are some options without using third party libraries:
// For that you will need to add reference to System.Runtime.Serialization
var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(@"{ ""Name"": ""Jon Smith"", ""Address"": { ""City"": ""New York"", ""State"": ""NY"" }, ""Age"": 42 }"), new System.Xml.XmlDictionaryReaderQuotas());
// For that you will need to add reference to System.Xml and System.Xml.Linq
var root = XElement.Load(jsonReader);
Console.WriteLine(root.XPathSelectElement("//Name").Value);
Console.WriteLine(root.XPathSelectElement("//Address/State").Value);
// For that you will need to add reference to System.Web.Helpers
dynamic json = System.Web.Helpers.Json.Decode(@"{ ""Name"": ""Jon Smith"", ""Address"": { ""City"": ""New York"", ""State"": ""NY"" }, ""Age"": 42 }");
Console.WriteLine(json.Name);
Console.WriteLine(json.Address.State);
See the link for more information about System.Web.Helpers.Json.
Update: Nowadays the easiest way to get the Web.Helpers
is to use the NuGet package.
If you don't care about earlier windows versions you can use the classes of the Windows.Data.Json
namespace:
// minimum supported version: Win 8
JsonObject root = Windows.Data.Json.JsonValue.Parse(jsonString).GetObject();
Console.WriteLine(root["Name"].GetString());
Console.WriteLine(root["Address"].GetObject()["State"].GetString());
Solution 4:
If .NET 4 is available to you, check out: http://visitmix.com/writings/the-rise-of-json (archive.org)
Here is a snippet from that site:
WebClient webClient = new WebClient();
dynamic result = JsonValue.Parse(webClient.DownloadString("https://api.foursquare.com/v2/users/self?oauth_token=XXXXXXX"));
Console.WriteLine(result.response.user.firstName);
That last Console.WriteLine is pretty sweet...