0

Web APIとJSONへの日付のシリアル化に慣れていない人のために、これが私がやろうとしていることです。

それは私にとっては機能していませんが、私の日付はまだ「/ Date(1039330800000-0700)/」としてシリアル化されます。

これが私のJsonNetFormatterです。

public class JsonNetFormatter : MediaTypeFormatter
{
    private JsonSerializerSettings _jsonSerializerSettings;

    public JsonNetFormatter(JsonSerializerSettings jsonSerializerSettings)
    {
        _jsonSerializerSettings = jsonSerializerSettings ?? new JsonSerializerSettings();

        // Fill out the mediatype and encoding we support 
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
        Encoding = new UTF8Encoding(false, true);
    }

    protected override bool CanReadType(Type type)
    {
        if (type == typeof(IKeyValueModel))
        {
            return false;
        }

        return true;
    }

    protected override bool CanWriteType(Type type)
    {
        return true;
    }

    protected override Task<object> OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext)
    {
        // Create a serializer 
        JsonSerializer serializer = JsonSerializer.Create(_jsonSerializerSettings);

        // Create task reading the content 
        return Task.Factory.StartNew(() =>
        {
            using (StreamReader streamReader = new StreamReader(stream, Encoding))
            {
                using (JsonTextReader jsonTextReader = new JsonTextReader(streamReader))
                {
                    return serializer.Deserialize(jsonTextReader, type);
                }
            }
        });
    }

    protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
    {
        // Create a serializer 
        JsonSerializer serializer = JsonSerializer.Create(_jsonSerializerSettings);

        // Create task writing the serialized content 
        return Task.Factory.StartNew(() =>
        {
            using (JsonTextWriter jsonTextWriter = new JsonTextWriter(new StreamWriter(stream, Encoding)) { CloseOutput = false })
            {
                serializer.Serialize(jsonTextWriter, value);
                jsonTextWriter.Flush();
            }
        });


    }
}

および私のGlobal.asax.csファイル:

public class WebApiApplication : System.Web.HttpApplication
{
    private static Logger Logger = NLog.LogManager.GetCurrentClassLogger();

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new WebApiApplication.Filters.ExceptionHandlingAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

    protected void Application_Start()
    {
        RegisterDependencies();

        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
        serializerSettings.Converters.Add(new IsoDateTimeConverter());
        GlobalConfiguration.Configuration.Formatters.Add(new JsonNetFormatter(serializerSettings));

        BundleTable.Bundles.RegisterTemplateBundles();
    }

    private void RegisterDependencies()
    {

        IUnityContainer container = new UnityContainer();
        container.RegisterInstance<IClientRepository>(new ClientRepository());

        GlobalConfiguration.Configuration.ServiceResolver.SetResolver(
            t =>
            {
                try
                {
                    return container.Resolve(t);
                }
                catch (ResolutionFailedException)
                {
                    return null;
                }
            },
            t =>
            {
                try
                {
                    return container.ResolveAll(t);
                }
                catch (ResolutionFailedException)
                {
                    return new List<object>();
                }
            });
    }

    /// <summary>
    /// Catches all exceptions.
    /// </summary>
    protected void Application_Error()
    {
        var exception = Server.GetLastError();

        Logger.Debug(exception);
    }
}

私が読んだことから、これは多くの人々のために働いています。何が欠けているのかわかりませんか?

4

1 に答える 1

0

デフォルトで構成に追加されている「古い」jsonフォーマッタを削除しましたか? あなたの代わりにデフォルトのフォーマッタが動作すると考えてください。あなたのものを追加する前に、デフォルトのJsonフォーマッタを削除してみてください

于 2012-06-20T17:54:59.767 に答える