除了默认的JSON和XML序列化器外,如果想使用其它格式的(比如二进制)序列化器,也是可以的。比如著名的Protobuf和Msgpack,它们都是二进制的序列化器,特点是速度快,体积小。使用方法如下。

1.定义MediaTypeFormatter,这里以定义MsgPack的formatter为例,主要代码如下。

2.WebApiConfig中注册,代码如下。

3.客户端调用(请求头中指定Accept),在.net端调用使用HttpClient,代码如下图。

附:MessagePackMediaTypeFormatter源代码。

using MsgPack;
using MsgPack.Serialization;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web; namespace HWA.OData.Site.Formatter
{
/// <summary>
/// MsgPack序列化器formatter
/// </summary>
public class MessagePackMediaTypeFormatter : MediaTypeFormatter
{
private readonly string _mime = "application/x-msgpack";
Func<Type, bool> IsAllowedType = (t) =>
{
if (!t.IsAbstract && !t.IsInterface && t != null && !t.IsNotPublic)
return true;
if (typeof(IEnumerable).IsAssignableFrom(t))
return true;
return false;
};
public MessagePackMediaTypeFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue(_mime));
}
public override bool CanWriteType(Type type)
{
if (type == null)
throw new ArgumentNullException("Type is null");
return IsAllowedType(type);
}
public override Task WriteToStreamAsync(Type type, object value, System.IO.Stream stream, HttpContent content, TransportContext transportContext)
{
if (type == null)
throw new ArgumentNullException("type is null");
if (stream == null)
throw new ArgumentNullException("Write stream is null");
var tcs = new TaskCompletionSource<object>();
if (type != typeof(string) && typeof(IEnumerable).IsAssignableFrom(type))
{
value = (value as IEnumerable<object>).ToList();
}
var serializer = MessagePackSerializer.Create<dynamic>();
serializer.Pack(stream, value);
tcs.SetResult(null);
return tcs.Task;
}
public override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContent content, IFormatterLogger formatterLogger)
{
var tcs = new TaskCompletionSource<object>();
if (content.Headers != null && content.Headers.ContentLength == 0)
return null;
try
{
var serializer = MessagePackSerializer.Create(type);
object result;
using (var mpUnpacker = Unpacker.Create(stream))
{
mpUnpacker.Read();
result = serializer.UnpackFrom(mpUnpacker);
}
tcs.SetResult(result);
}
catch (Exception e)
{
if (formatterLogger == null) throw;
formatterLogger.LogError(String.Empty, e.Message);
tcs.SetResult(GetDefaultValueForType(type));
}
return tcs.Task;
}
public override bool CanReadType(Type type)
{
if (type == null)
throw new ArgumentNullException("type is null");
return IsAllowedType(type);
}
}
}

重点关注之自定义序列化方式(Protobuf和Msgpack)的更多相关文章

  1. WeihanLi.Redis自定义序列化及压缩方式

    WeihanLi.Redis自定义序列化及压缩方式 Intro WeihanLi.Redis 是基于 StackExchange.Redis 的扩展,提供了一些常用的业务组件和对泛型的更好支持,默认使 ...

  2. java序列化和反序列化及序列化方式

    平时我们在Java内存中的对象,是无 法进行IO操作或者网络通信的,因为在进行IO操作或者网络通信的时候,人家根本不知道内存中的对象是个什么东西,因此必须将对象以某种方式表示出来,即 存储对象中的状态 ...

  3. .Net Core 自定义序列化格式

    序列化对大家来说应该都不陌生,特别是现在大量使用WEBAPI,JSON满天飞,序列化操作应该经常出现在我们的代码上. 而我们最常用的序列化工具应该就是Newtonsoft.Json,当然你用其它工具类 ...

  4. Newtonsoft.Json高级用法 1.忽略某些属性 2.默认值的处理 3.空值的处理 4.支持非公共成员 5.日期处理 6.自定义序列化的字段名称

    手机端应用讲究速度快,体验好.刚好手头上的一个项目服务端接口有性能问题,需要进行优化.在接口多次修改中,实体添加了很多字段用于中间计算或者存储,然后最终用Newtonsoft.Json进行序列化返回数 ...

  5. Java Serializable接口(序列化)理解及自定义序列化

      1 Serializable接口 (1)简单地说,就是可以将一个对象(标志对象的类型)及其状态转换为字节码,保存起来(可以保存在数据库,内存,文件等),然后可以在适当的时候再将其状态恢复(也就是反 ...

  6. Android进程通信之一:两种序列化方式

    2月下旬辞职了,去海南度假到现在,领略了一把三亚风情也算任性和 然而这样任性带来的后果就是..不行了我必须吐槽一句.. 没毕业的找工作就这么难嘛!投了57家一家面试机会都没有,好歹给个面试机会啊!!本 ...

  7. SpringBoot修改Redis序列化方式

    前言 由于Springboot默认提供了序列化方式并不是非常理想,对于高要求的情况下,序列化的速度和序列化之后大小有要求的情况下,不能满足,所以可能需要更换序列化的方式. 这里主要记录更换序列化的方式 ...

  8. 几种序列化协议(protobuf,xstream,jackjson,jdk,hessian)相关数据对比

    测试结果 序列化数据对比 bytes字节数对比 具体的数字:   protobuf jackson xstream Serializable hessian2 hessian2压缩 hessian1 ...

  9. 自定义兼容多种Protobuf协议的编解码器

    <从零开始搭建游戏服务器>自定义兼容多种Protobuf协议的编解码器 直接在protobuf序列化数据的前面,加上一个自定义的协议头,协议头里包含序列数据的长度和对应的数据类型,在数据解 ...

随机推荐

  1. 《转》Ubuntu 12.04常用的快捷键

    Ubuntu 12.04常用的快捷键   超级键操作   1.超级键(Win键)–打开dash.   www.2cto.com   2.长按超级键– 启动Launcher.并快捷键列表.   3.按住 ...

  2. Eclipse使用Jetty(转)

    eclipse 与 jetty 结合的最佳实践 http://www.cnblogs.com/mignet/archive/2011/12/04/eclipse_jetty_perfect_integ ...

  3. mysql概要(十一)存储引擎

    1.数据库对同样的数据可以不同的方式存储和管理,每种方式对应一种引擎. 1.1定义: 2.引擎种类的特点:

  4. Google账户_GooglePlay_关联

    PS:这过程叫一个折腾...穷逼的无奈啊... 1. 1.1. 网上搜到说,安装 google play & google框架服务,手机需要root,没去证实这个事情... 用了之前的 And ...

  5. [转载] 分析Linux内核创建一个新进程的过程

    http://blog.luoyuanhang.com/2015/07/27/%E5%88%86%E6%9E%90Linux%E5%86%85%E6%A0%B8%E5%88%9B%E5%BB%BA%E ...

  6. 学习笔记day6:position index结合

    z-index属性适用于定位元素(position 属性值为 relative 或 absolute 或 fixed的对象),用来确定定位元素在垂直于显示屏方向(称为Z轴)上的层叠顺序(stack o ...

  7. Ubuntu Server14.04 32位安装odoo8.0简单方法

    一.wget -O - https://nightly.odoo.com/odoo.key | apt-key add - 二.echo "deb http://nightly.odoo.c ...

  8. Oracle SQL 调优之 sqlhc

    SQL 执行慢,如何 快速准确的优化. sqlhc 就是其中最好工具之一 通过获得sql所有的执行计划,列出实际的性能的瓶颈点,列出 sql 所在的表上的行数,每一列的数据和分布,现有的索引,sql ...

  9. Falcon Genome Assembly Tool Kit Manual

    Falcon Falcon: a set of tools for fast aligning long reads for consensus and assembly The Falcon too ...

  10. [转]Android_气泡效果

    最近在看以前在eoe上收藏的一些源代码,准备将这些代码加上一些自己的注释,然后贴出来,方便自己日后查阅,和刚入门的人来学习. 今天先看一个气泡窗口,先看一下效果图和目录结构,然后再上代码 通过第一幅图 ...