C#的JSON库

wei*_*in8 76 c# json

Microsoft是否提供任何库以在C#中使用JSON?如果没有,你推荐什么开源库?

Amy*_*Amy 77

JSON.Net

  • 不要使用JavaScriptSerializer,它比我基准测试的大多数其他JSON序列化器慢40倍. (7认同)
  • 使用JSON.NET而不是System.Web.Script.Serialization.JavaScriptSerializer有什么好处? (5认同)
  • 它允许你使用类属性,而只是序列化字符串,一个......还有更多.. (3认同)

myt*_*thz 19

您还应该尝试我的ServiceStack JsonSerializer - 它是目前最快的.NET JSON序列化程序,基于领先的JSON序列化程序的基准测试,并支持序列化任何POCO类型,DataContracts,列表/字典,接口,继承,后期绑定对象,包括匿名类型等

基本例子

var customer = new Customer { Name="Joe Bloggs", Age=31 };
var json = customer.ToJson();
var fromJson = json.FromJson<Customer>(); 
Run Code Online (Sandbox Code Playgroud)

注意:如果性能对您不重要,请仅使用Microsofts JavaScriptSerializer,因为我不得不将其从基准测试中删除,因为它比其他JSON序列化器慢40x-100x.


Ty.*_*Ty. 14

.net框架通过JavaScriptSerializer支持JSON.这是一个很好的例子,可以帮助您入门.

using System.Collections.Generic;
using System.Web.Script.Serialization;

namespace GoogleTranslator.GoogleJSON
{
    public class FooTest
    {
        public void Test()
        {
            const string json = @"{
              ""DisplayFieldName"" : ""ObjectName"", 
              ""FieldAliases"" : {
                ""ObjectName"" : ""ObjectName"", 
                ""ObjectType"" : ""ObjectType""
              }, 
              ""PositionType"" : ""Point"", 
              ""Reference"" : {
                ""Id"" : 1111
              }, 
              ""Objects"" : [
                {
                  ""Attributes"" : {
                    ""ObjectName"" : ""test name"", 
                    ""ObjectType"" : ""test type""
                  }, 
                  ""Position"" : 
                  {
                    ""X"" : 5, 
                    ""Y"" : 7
                  }
                }
              ]
            }";

            var ser = new JavaScriptSerializer();
            ser.Deserialize<Foo>(json);
        }
    }

    public class Foo
    {
        public Foo() { Objects = new List<SubObject>(); }
        public string DisplayFieldName { get; set; }
        public NameTypePair FieldAliases { get; set; }
        public PositionType PositionType { get; set; }
        public Ref Reference { get; set; }
        public List<SubObject> Objects { get; set; }
    }

    public class NameTypePair
    {
        public string ObjectName { get; set; }
        public string ObjectType { get; set; }
    }

    public enum PositionType { None, Point }
    public class Ref
    {
        public int Id { get; set; }
    }

    public class SubObject
    {
        public NameTypePair Attributes { get; set; }
        public Position Position { get; set; }
    }

    public class Position
    {
        public int X { get; set; }
        public int Y { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)


Jam*_*ack 7

如果你看这里,你会在C#上看到几个不同的JSON库.

http://json.org/

您将找到LINQ以及其他一些版本.C#和JSON大约有7个库.