Jil.DeserializationException: «Ожидаемая цифра» - PullRequest
2 голосов
/ 19 июня 2019

Я пытаюсь реализовать сериализатор Jil в WebAPI (C #).При десериализации выдает ошибку типа «Jil.DeserializationException:« Ожидаемая цифра »».Я приложил примеры кода.

WebApiConfig.cs

        config.Formatters.Clear();
        var _jilOptions = new Options(dateFormat: DateTimeFormat.ISO8601, excludeNulls: true, includeInherited: true);
        config.Formatters.Add(new JilFormatter(_jilOptions));

JilFormatter.cs

public class JilFormatter : MediaTypeFormatter
    {
        private static readonly MediaTypeHeaderValue _applicationJsonMediaType = new MediaTypeHeaderValue("application/json");
        private static readonly MediaTypeHeaderValue _textJsonMediaType = new MediaTypeHeaderValue("text/json");
        private readonly Options _options;

        public JilFormatter(Options options)
        {
            _options = options;
            SupportedMediaTypes.Add(_applicationJsonMediaType);
            SupportedMediaTypes.Add(_textJsonMediaType);

            SupportedEncodings.Add(new UTF8Encoding(false, true));
            SupportedEncodings.Add(new UnicodeEncoding(false, true, true));
        }

        public override bool CanReadType(Type type)
        {
            if (type == null)
                return false;
            return true;
        }

        public override bool CanWriteType(Type type)
        {
            if (type == null)
                return false;
            return true;
        }

        public override Task<object> ReadFromStreamAsync(Type type, Stream input, HttpContent content, IFormatterLogger formatterLogger)
        {
            var reader = new StreamReader(input);
            var deserialize = TypedDeserializers.GetTyped(type);
            var result = deserialize(reader, _options);
            return Task.FromResult(result);
        }

        public override Task WriteToStreamAsync(Type type, object value, Stream output, HttpContent content, TransportContext transportContext)
        {
            var writer = new StreamWriter(output);
            JSON.Serialize(value, writer, _options);
            writer.Flush();
            return Task.FromResult(true);
        }
    }

Класс TypedDeserializers:

static class TypedDeserializers
    {
        private static readonly ConcurrentDictionary<Type, Func<TextReader, Options, object>> _methods;
        private static readonly MethodInfo _method = typeof(JSON).GetMethod("Deserialize", new[] { typeof(TextReader), typeof(Options) });

        static TypedDeserializers()
        {
            _methods = new ConcurrentDictionary<Type, Func<TextReader, Options, object>>();
        }

        public static Func<TextReader, Options, object> GetTyped(Type type)
        {
            return _methods.GetOrAdd(type, CreateDelegate);
        }

        private static Func<TextReader, Options, object> CreateDelegate(Type type)
        {
            return (Func<TextReader, Options, object>)_method
                .MakeGenericMethod(type)
                .CreateDelegate(typeof(Func<TextReader, Options, object>));
        }
    }

ReuestTest.cs

public class ReuestTest
    {        
        public long UserId { get; set; }

        public long MobileDeviceId { get; set; }

        public bool IsInitialLoad { get; set; }

    }

testController.cs

[HttpPost]
public string GetAllDispatchestest(ReuestTest request)
{
return something;
}

Исключение:

{
    "Message": "An error has occurred.",
    "ExceptionMessage": "Expected digit",
    "ExceptionType": "Jil.DeserializationException",
    "StackTrace": "   at Jil.Deserialize.Methods._ReadInt64(TextReader reader)\r\n   at _DynamicMethod4(TextReader , Int32 )\r\n   at Jil.JSON.Deserialize[T](TextReader reader, Options options)\r\n   at api.myapi.com.Utilities.JilFormatter.ReadFromStreamAsync(Type type, Stream input, HttpContent content, IFormatterLogger formatterLogger) in F:\\Projects\\myapi\\myapi.Solution\\api.myapi.com\\Utilities\\JilFormatter.cs:line 51\r\n   at System.Net.Http.Formatting.MediaTypeFormatter.ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n   at System.Net.Http.HttpContentExtensions.<ReadAsAsyncCore>d__0`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.ModelBinding.FormatterParameterBinding.<ExecuteBindingAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.HttpActionBinding.<ExecuteBindingAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
}
...