Newtonsoft Json自定义Serialization过程

The IContractResolver interface provides a way to customize how the JsonSerializer serializes and deserializes .NET objects to JSON without placing attributes on your classes.

Anything that can be set on an object, collection, property, etc, using attributes or methods to control serialization can also be set using an IContractResolver.

For performance you should create a contract resolver once and reuse instances when possible. Resolving contracts is slow and implementations of IContractResolver typically cache contracts.

未自定义之前的数据结构
使用了自定义序列化的camelcase的response result

以上例子是直接使用newtonsoft提供的camelCase的resolver,当然我们也可以overrider default resolver所提供的的CreateContract方法,定义我们自己serialization逻辑。

示例代码

上述示例是将object中的所有的datetime和datetimeoffset类型都转换成JavaScript中是时间类型,也就是时间戳类型。

PS: demo中还使用了Bogus第三库,来生成随机对象。

Bogus生成faker对象
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容