Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to parse JSON in C#

Tags:

json

c#

asp.net

I was wondering what is the most efficient way to parse JSON in C#? And by efficient I mean the one with the lower response time. I am trying to parse a large amount of data using a couple of methods, and response time in both of these methods are high. Can anyone tell me the difference between the following methods? Is there an alternative that would let me parse with a lower response time?

Option 1:

HttpWebRequest request = WebRequest.Create(jsonURL) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    if (response.StatusCode != HttpStatusCode.OK)
        throw new Exception(String.Format(
        "Server error (HTTP {0}: {1}).",
        response.StatusCode,
        response.StatusDescription));
    DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(obj));
    object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
}  

Option 2:

var json = new WebClient().DownloadString(jsonURL);
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
    DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(obj));
    object objResponse = jsonSerializer.ReadObject(ms);
}  
like image 1000
Gonzalo Avatar asked Apr 18 '13 16:04

Gonzalo


3 Answers

You can find a comparison in following link.

The libraries tested:

http://sagistech.blogspot.com/2010/03/parsing-twitter-json-comparing-c.html

  • Json.NET - A popular C# JSON library.
  • Gapi.NET - Gapi.NET is not a JSON parsing library, but it contains JSON parsing routines.
  • Procurios - Yet another C# JSON library. See also this blog post how to use it to parse Twiter data.
  • JavaScriptSerializer - .NET 3.5 built-in JSON parser.
  • DataContractJsonSerializer - .NET 3.5 built-in JSON parser.
  • AjaxPro - A C# AJAX library.

enter image description here


Updated:

Added this information based on Matt Johnson's comment

http://theburningmonk.com/2011/11/performance-test-json-serializers-part-ii/

like image 69
Chamika Sandamal Avatar answered Oct 31 '22 11:10

Chamika Sandamal


The first method has the opportunity to make less copies of the data. But I have trouble believing that either method makes a measurable difference. Your real cost is going to be network costs.

like image 39
Brandon Avatar answered Oct 31 '22 12:10

Brandon


Still in an early stage but I build a code generator on top of Json.NET that eliminates reflection and speeds up deserialization by a factor of 4.

Checkout CGbR JSON target.

[DataContract]
public partial class Root
{
    [DataMember]
    public int Number { get; set; }

    [DataMember]
    public Partial[] Partials { get; set; }

    [DataMember]
    public IList<ulong> Numbers { get; set; }
}

will generate a partial class:

public Root FromJson(JsonReader reader)
{
    while (reader.Read())
    {
        // Break on EndObject
        if (reader.TokenType == JsonToken.EndObject)
            break;

        // Only look for properties
        if (reader.TokenType != JsonToken.PropertyName)
            continue;

        switch ((string) reader.Value)
        {
            case "Number":
                reader.Read();
                Number = Convert.ToInt32(reader.Value);
                break;

            case "Partials":
                reader.Read(); // Read token where array should begin
                if (reader.TokenType == JsonToken.Null)
                    break;
                var partials = new List<Partial>();
                while (reader.Read() && reader.TokenType == JsonToken.StartObject)
                    partials.Add(new Partial().FromJson(reader));
                Partials = partials.ToArray();
                break;

            case "Numbers":
                reader.Read(); // Read token where array should begin
                if (reader.TokenType == JsonToken.Null)
                    break;
                var numbers = new List<ulong>();
                while (reader.Read() && reader.TokenType != JsonToken.EndArray)
                    numbers.Add(Convert.ToUInt64(reader.Value));
                Numbers = numbers;
                break;

        }
    }

    return this;
}
like image 26
Toxantron Avatar answered Oct 31 '22 11:10

Toxantron