简体   繁体   English

在C#中解析JSON的最有效方法

[英]Most efficient way to parse JSON in C#

I was wondering what is the most efficient way to parse JSON in C#? 我想知道在C#中解析JSON的最有效方法是什么? 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: 选项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: 选项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);
}  

You can find a comparison in following link. 您可以在以下链接中找到比较。

The libraries tested: 测试的库:

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

  • Json.NET - A popular C# JSON library. Json.NET - 一个流行的C#JSON库。
  • Gapi.NET - Gapi.NET is not a JSON parsing library, but it contains JSON parsing routines. Gapi.NET - Gapi.NET不是JSON解析库,但它包含JSON解析例程。
  • Procurios - Yet another C# JSON library. Procurios - 又一个C#JSON库。 See also this blog post how to use it to parse Twiter data. 另请参阅此博客文章,了解如何使用它来解析Twiter数据。
  • JavaScriptSerializer - .NET 3.5 built-in JSON parser. JavaScriptSerializer - .NET 3.5内置JSON解析器。
  • DataContractJsonSerializer - .NET 3.5 built-in JSON parser. DataContractJsonSerializer - .NET 3.5内置JSON解析器。
  • AjaxPro - AC# AJAX library. AjaxPro - AC#AJAX库。

在此输入图像描述


Updated: 更新:

Added this information based on Matt Johnson's comment 根据Matt Johnson的评论添加了此信息

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

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. 您的实际成本将是网络成本。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace Example
{
public static class JavascriptSerializator
{
    /// <summary>
    /// Serializes object to JSON from Microsoft
    /// </summary>
    /// <param name="objectForSerialization"></param>
    /// <returns></returns>
    public static string SerializeMJSON(this object objectForSerialization)
    {
        try
        {
            System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer();

            return s.Serialize(objectForSerialization);
        }
        catch (Exception ex)
        {
            /// Handle exception and throw it ...
        }

    }

    /// <summary>
    /// Deserializes object from Microsoft JSON string
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="str"></param>
    /// <returns></returns>
    public static T DeserializeMJSON<T>(this string str)
    {
        try
        {
            System.Web.Script.Serialization.JavaScriptSerializer s = new System.Web.Script.Serialization.JavaScriptSerializer();

            return s.Deserialize<T>(str);
        }
        catch (Exception ex)
        {
            //// Handle the exception here...
        }

    }
}

} }

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. 仍处于早期阶段,但我在Json.NET之上构建了一个代码生成器,它消除了反射并加速了反序列化4倍。

Checkout CGbR JSON target . 结帐CGbR JSON目标

[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;
}

Out of curiosity, I've had both JSON.NET 5.0 r8 and my own (only ~ 500 lines of code) toy JSON parser eat various JSON file sizes with or without loops, from the few dozens character ballpark, to one 180 mb JSON file, of, say, "real" data. 出于好奇,我有JSON.NET 5.0 r8和我自己的(只有~500行代码)玩具JSON解析器吃各种JSON文件大小有或没有循环,从几十个角色球场到一个180 MB JSON文件,例如“真实”数据。

The sample data (including a 12mb JSON but excluding the 180mb one that can be found elsewhere) with accompanying details, such as an example of parsing from a stream to deserialize into POCO (strongly typed) objects, can be found here: 可以在此处找到样本数据(包括12mb JSON,但不包括可在其他地方找到的180mb)以及附带的详细信息,例如从流解析到反序列化为POCO(强类型)对象的示例:

https://github.com/ysharplanguage/FastJsonParser https://github.com/ysharplanguage/FastJsonParser

'Hope it helps. '希望能帮助到你。

PS Good links to know about, btw, already provided by Chamika in his comment. PS很好的链接,知道,顺便说一下,Chamika已经在他的评论中提供了。

EDIT 编辑

Before I forget (or just in case it was overlooked), here's the kind of must-know/must-read, IMO, on the importance of not stressing the CLR's large object heap whenever possible, thanks to streamed reading of the JSON your code consumes, especially in the context of a web server environment: 在我忘记之前(或者只是在它被忽略的情况下),这是必须知道/必须阅读的那种,IMO,尽可能强调CLR的大对象堆的重要性,这要归功于流式读取JSON您的代码消耗,特别是在Web服务器环境的上下文中:

http://insidethecpu.wordpress.com/2013/06/19/json-parsing/ http://insidethecpu.wordpress.com/2013/06/19/json-parsing/

PPS (Hence the very last test in the Program.cs to test/showcase my toy parser that I linked to, above) PPS(因此是Program.cs中的最后一次测试,用于测试/展示我链接到的玩具解析器,上面)

'HTH! “HTH!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM