Language: EN

crear-y-leer-ficheros-json-facilmente-en-c-con-jsonnet

Easily Create and Read Json Files in C# with JsonNET

In this post we are going to see how to easily and efficiently work with Json files in a C# program thanks to the Json.NET library.

There is no doubt that the Json format has become one of the standards for exchanging structured data between multi-platform Web services.

The Json format has some advantages over its competitors (such as xml), such as a smaller file size, being easier to understand by a person, or faster generation and processing.

Although we usually associate Json files with Javascript, the main programming languages have libraries for working with Json files comfortably.

Of course, C# is no exception. The .NET framework natively supports Json from version 4.0. But its use is even simpler and more efficient thanks to the popular open source library Json.NET, whose code is available at https://github.com/JamesNK/Newtonsoft.Json.

Using the Json.NET library

Adding the Json.NET library to our program is easy since it is available as a Nutget package. We just have to add it through the package manager and we will be ready to work.

jsonnet-nutget

Let’s briefly see the use of Json.NET. To do this, we create an object that has the structure of the Json we want to work with.

public class Product
{
  public string Name { get; set; }
  public DateTime ExpiryDate { get; set; }
  public decimal Price { get; set; }
  public string[] Sizes { get; set; }
}

Serialize Json

To perform serialization, we simply have to call the SerializeObject function.

var product = new Product
{
  Name = "Apple",
  ExpiryDate = new DateTime(2008, 12, 28),
  Price = 3.99M,
  Sizes = new[] {"Small", "Medium", "Large"}
};      

string json = JsonConvert.SerializeObject(product);

Now with this string we can do whatever we need, such as saving it to a file.

string path = @"c:\product.json";
System.IO.File.WriteAllText(path, json);

Or send it through an HTTP request.

var request = (HttpWebRequest)WebRequest.Create(url); 
request.Method = "POST"; 
request.ContentType = "application/xml; charset=utf-8"; 
request.Timeout = 30000; 

string json = JsonConvert.SerializeObject(product);
byte[] byteArray = Encoding.UTF8.GetBytes(json);
request.ContentLength = byteArray.Length;

var dataStream = new StreamWriter(request.GetRequestStream()); 
dataStream.Write(byteArray); 
dataStream.Close();

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
  dataStream = response.GetResponseStream ();    
  using (Stream stream = response.GetResponseStream())
  {
    using (StreamReader reader = new StreamReader(stream))
    {
      string responseFromServer = reader.ReadToEnd ();
    }
  }
}

Deserializing Json

Parsing a Json file is equally simple thanks to the DeserializeObject function,

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);

Of course, the string can be obtained in any available way. For example, reading it from an existing file.

string path = @"c:\product.json";
using (StreamReader jsonStream = File.OpenText(path))
{
    var json = jsonStream.ReadToEnd();
    Product product = JsonConvert.DeserializeObject<Product>(json);
}

Or as a response through an Http request

string url = @"http://www.yourJsonUrlAddress.com";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
    var json = reader.ReadToEnd();
    Product product = JsonConvert.DeserializeObject<Product>(json);
}

These are only some of the many available functions in Json.NET. For more information, see the examples available on the library’s website.

As we can see, Json.NET makes it trivial to work with Json files in C#. Without a doubt, a reference library in .NET, and a tool to add to our list of favorites.