jsmn (pronounced like 'jasmine') is a minimalistic JSON parser in C. It can be easily integrated into the resource-limited projects or embedded systems. You can find more information about JSON format at json.org.
Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.
Parsing JSON in C using microjson JavaScript Object Notation, or JSON, is a commonly used human-readable format for transmitting data objects as key-value pairs. Developed originally for server-browser communication, the use of JSON has since expanded into a universal data interchange format.
If you need to parse a JSON string that returns a dictionary, then you can use the json. loads() method. If you need to parse a JSON file that returns a dictionary, then you can use the json. load() method.
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:
JsonIgnore
and JsonProperty
can be added to a class to customize how a class is serializedLook 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);
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;
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());
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...
Another native solution to this, which doesn't require any 3rd party libraries but a reference to System.Web.Extensions is the JavaScriptSerializer. This is not a new but a very unknown built-in features there since 3.5.
using System.Web.Script.Serialization;
..
JavaScriptSerializer serializer = new JavaScriptSerializer();
objectString = serializer.Serialize(new MyObject());
and back
MyObject o = serializer.Deserialize<MyObject>(objectString)
.NET core 3.0 comes with System.Text.Json
built-in which means you can deserialize/serialize JSON without using a third-party library.
To serialize your class(es) to JSON string:
var json = JsonSerializer.Serialize(order);
To deserialize the JSON into a strongly typed class:
var order = JsonSerializer.Deserialize<Order>(json);
So if you have a class like below:
public class Order
{
public int Id { get; set; }
public string OrderNumber { get; set; }
public decimal Balance { get; set; }
public DateTime Opened { get; set; }
}
var json = JsonSerializer.Serialize(order);
// creates JSON ==>
{
"id": 123456,
"orderNumber": "ABC-123-456",
"balance": 9876.54,
"opened": "2019-10-21T23:47:16.85",
};
var order = JsonSerializer.Deserialize<Order>(json);
// ==> creates the above class
One thing to note is that System.Text.Json
does not automatically handle camelCase
JSON properties when using your own code (however, it does when using MVC/WebAPI requests and the model binder).
To resolve this you need to pass JsonSerializerOptions
as a parameter.
JsonSerializerOptions options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase, // set camelCase
WriteIndented = true // write pretty json
};
// pass options to serializer
var json = JsonSerializer.Serialize(order, options);
// pass options to deserializer
var order = JsonSerializer.Deserialize<Order>(json, options);
System.Text.Json is also available for .Net Framework and .Net Standard as a Nu-get package System.Text.Json
You could also have a look at the DataContractJsonSerializer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With