LoginSignup
1
1

More than 5 years have passed since last update.

ASP.NET Web API で Utf8Json を使ってみる

Last updated at Posted at 2017-10-13

最速を体験したくてやってみました!
Utf8Json

参考:ASP.NET Web API で Jil JSON Serializer を使ってみる

軽量APIではデフォルト(Json.NET)との違いが見いだせず・・・
※実装理解していないので使い方が間違っているかも??

サンプルコード

Utf8JsonMediaTypeFormatter.cs
public class Utf8JsonMediaTypeFormatter : MediaTypeFormatter
{
    public Utf8JsonMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));

        SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true));
        SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true));
    }

    public override bool CanReadType(Type type)
    {
        if (type == null)
        {
            throw new ArgumentNullException("type");
        }
        return true;
    }

    public override bool CanWriteType(Type type)
    {
        if (type == null)
        {
            throw new ArgumentNullException("type");
        }
        return true;
    }

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        return Task.FromResult(JsonSerializer.NonGeneric.Deserialize(type, readStream));
    }

    public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
    {
        JsonSerializer.NonGeneric.Serialize(type, writeStream, value);
        return Task.FromResult(writeStream);
    }
}
WebApiConfig.cs
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Formatters.RemoveAt(0);
        config.Formatters.Insert(0, new Utf8JsonMediaTypeFormatter());

        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1