Remove sensitive structures: MethodTable and FieldDesc. (Fast reflection for static fields is no longer supported, but has no effect on json.)
Supports serialization and deserialization of very large files.
Easy to use 简单使用
publicclassDemo{publicintId{get;set;}publicintName{get;set;}publicstaticvoidMain(){varjson= JsonFormatter.SerializeObject(new{ Id =123, Name ="Dogwei"});vardic= JsonFormatter.DeserializeObject<Dictionary<string,object>>(json);varobj= JsonFormatter.DeserializeObject<Demo>(json);}}
Supported data structures and types 支持的数据类型和结构
bool,byte,sbyte,short,ushort,char,int,uint,long,ulong,IntPtr,UIntPtr,float,double,decimal,string,enum,DateTime,DateTimeOffset,TimeSpan,Guid,BigInteger,Complex,DBNull,Nullable<T>,Tuple<...>,ValueTuple<...>,Version,Uri,Assembly,Type,MemberInfo,MethodInfo,FieldInfo,PropertyInfo,ConstructorInfo,EventInfo,Array,Multidimensional-Arrays,IList,IList<T>,ICollection,ICollection<T>,IDictionary,IDictionary<TKey,TValue>,IEnumerable,IEnumerable<T>,DataSet,DataTable,DataRow,DbRowObject,DbDataReader...
Other types are treated asobject 其他类型当作对象处理
Supported platforms and runtimes 支持的平台和运行时
.NET Framework 2.0+, .NET Core 2.0+, .NET Standard 2.0+, MONO, MONO AOT, MONO FULL-AOT,
Unity, Xamarin.iOS, Xamarin.Android
Uncertain:Unity IL2CPP
Unsupported: Sliverlight
Note:
.NET Core use the Core version, and other platforms use the Framework version or Standard version.
Because the Core version is performance-optimized.
the Framework version and Standard version are optimized for compatibility.
the Framework version and Standard version can run directly on AOT platforms.
注意:
.NET Core 请使用 Core 版本,其他平台和运行时请使用 Framework 版本或 Standard 版本。
因为 Core 版本专为性能优化,Framework 版本和 Standard 版本为兼容性优化。
Framework 版本和 Standard 版本可以直接在 AOT 平台上运行。
Supported features 支持的功能
LoopReferencingNull:
Objects that appear a loop reference during serialization are treated as Null.
在序列化时出现循环引用的对象将用 Null 表示。
MultiReferencingReference:
Allow use { "$ref": "#/obj/1/target" } to represent objects that are repeatedly referenced.
允许使用 { "$ref": "#/obj/1/target" } 写法表示重复引用的对象。
AsOrderedObjectDeserialize
Perform as-ordered object fields parsing, which can improve parsing performance of ordered Json objects.
执行假定有序的对象字段解析,这可以提高有序 Json 对象的解析性能。
DeflateDeserialize
Perform deflate(no spaces) Json parsing, which can improve parsing performance.
执行紧凑(无空白字符)的 Json 解析,这可以提高解析性能。
Indented
Json indents and wraps during serialization, which makes Json beautiful.
序列化时对 Json 进行缩进和换行,让 Json 变得好看。
CamelCaseWhenSerialize
Convert the fields name in the object to camel case during serialization.
序列化时,将对象中的字段名称转换为骆驼命名法。 ::: new { Name = "Dogwei" } -> { "name": "Dogwei" }
IgnoreNull | IgnoreZero | IgnoreEmptyString
Null, 0, "" values are ignored during serialization.
序列化时分别跳过 Null, 0 和 "" 值。 ::: { A = (string)null, B = 0, C = "", D = 1 } -> { "D": 1 }
For more features, please see Swifter.Json.JsonFormatterOptions enum.
更多功能请看 Swifter.Json.JsonFormatterOptions 配置项。
Performance 性能
ServiceStack.Json, Jil, LitJson, NetJson and etc libraries are not shown because there are too many errors; if necessary, you can clone the test program on GitHub and run. Most of the Json serialization libraries of .NET have been included.
(4) Use Swifter.Json on AspNetCore. 在 AspNetCore 上使用 Swifter.Json
First, reference the latest version of Swifter.Extensions.AspNetCore package on Nuget. And configure as follows.
首先在 Nuget 上引用最新的 Swifter.Extensions.AspNetCore 包,并如下配置。
/** Configure */publicclass Startup
{publicvoidConfigureServices(IServiceCollectionservices){
services.ConfigureJsonFormatter();}}In this way,when the client use the application/json header request,it will use Swifter.Json serialize results and deserialize parameters.
Or you can use the JsonResult to explicitly return Json content.
这样配置后,当客户端使用 application/json 头请求时,就会使用 Swifter.Json 序列化返回值或反序列化参数。
或者您可以使用 JsonResult 显式的返回 Json 内容。
In Newtonsoft.Json, we can define the data type of the $data field through the $type pseudo-field to avoid data type ambiguity in RPC. Does Swifter.Json support the above features?
下面时错误信息
C:\Program Files\Unity\Hub\Editor\2019.3.1f1\Editor\Data\Resources\PackageManager\BuiltInPackages\com.unity.ugui\Runtime\UI\Core\Layout\LayoutUtility.cs(134,74): error CS0433: The type 'Func<T1, TResult>' exists in both 'Swifter.Core, Version=1.5.0.3, Culture=neutral, PublicKeyToken=5c52005388a7b388' and 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'
An unhandled exception occurred while processing the request.
ArgumentNullException: Value cannot be null. (Parameter 'encoding')
Microsoft.AspNetCore.Mvc.Infrastructure.MemoryPoolHttpResponseStreamWriterFactory.CreateWriter(Stream stream, Encoding encoding)
但是,这种行为在 Asp.Net Core 3.0 Preview 8 默认生成的模板程序中会正常返回一个字符串。
public class ApirolesMetaData
{
[RWField(Access = RWFieldAccess.Ignore)]
public string Name { get; set; }
}
[ModelMetadataType(typeof(ApirolesMetaData))]
public partial class Apiroles
{
public string Name { get; set; }
}
FastObjectRW.DefaultOptions &= ~FastObjectRWOptions.CannotSetException;
var obj1 = new ApiResult();
var obj2 = JsonFormatter.DeserializeObject(JsonFormatter.SerializeObject(obj1), typeof(ApiResult));
public class ApiResult
{
[RWField(Name = "timestamp", Order = 99)]
[RWObject(CannotSetException = RWBoolean.No)]
public long Timestamp => (long)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalMilliseconds;
}
class ApiResult
{
[RWField(Name = "code", Order = 1)]
public int Code { get; set; }
[RWField(Name = "msg", Order = 2)]
public string Message { get; set; }
[RWField(Name = "timestamp", Order = 3)]
public long Timestamp => (long)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalMilliseconds;
public static ApiResult Succeed() => new ApiResult { Code = 200 };
public static ApiResult Failed(int code, string errorMessage)
=> new ApiResult { Code = code, Message= errorMessage };
}
class ApiResult<T> : ApiResult
{
public T Data { get; set; }
public static ApiResult<T> Succeed(T data) => new ApiResult<T> { Code = 200, Data = data };
}
定义了一个用来测试的类
class Student
{
public int No { get; set; }
public string Name { get; set; }
public string Addr { get; set; }
[RWFormat("yyyy-MM-dd HH:mm:ss")]
public DateTime Birthday { get; set; }
}
测试程序
class Program
{
static void Main(string[] args)
{
var result1 = ApiResult<Student>.Succeed(new Student() { No = 1, Name = "张三", Addr = null, Birthday = DateTime.Now });
var json1 = JsonFormatter.SerializeObject(result1);
var json2 = JsonFormatter.SerializeObject(result1, JsonFormatterOptions.IgnoreNull);
var result2 = ApiResult.Failed(400, "网络连接错误");
var json3 = JsonFormatter.SerializeObject(result2);
var json4 = JsonFormatter.SerializeObject(result2, JsonFormatterOptions.IgnoreNull);
var stu = new { No = 1, Name = "张三", Addr = default(string), Birthday = DateTime.Now };
var json5 = JsonFormatter.SerializeObject(ApiResult<dynamic>.Succeed(stu));
Console.WriteLine(json1);
Console.WriteLine(json2);
Console.WriteLine(json3);
Console.WriteLine(json4);
Console.WriteLine(json5);
Console.ReadKey();
}
}
I have a DateTime that is in UTC-6 timezone, which serializes like this in other serializers:
"2020-06-01T00:00:00-06:00"
Using Swifter.Json, it serializes as:
"2020-06-01T00:00:00-07:00"
...which happens to be my local timezone, but not the timezone of the DateTime I'm giving it.