Ulf Åkerstedt
Ulf Åkerstedt

Reputation: 3236

Control deserialization in Nancy 2.0.0

How do I instruct Nancy 2.0.0-clinteastwood to do custom deserialization to DateTime such as from this json

{
    "someDate": "2018-09-18"
}

into a DateTime property such as in an instance of this C# class

public class SomeClass
{
    public DateTime SomeDate { get; set; }
}

?

In pre-2.0.0 versions you could apparently assign your custom JavaScriptPrimitiveConverter by a call to the static JsonSettings for instance in ApplicationStartup like this

Nancy.Json.JsonSettings.PrimitiveConverters.Add(new CustomJavaScriptPrimitiveConverter())

and I could have implemented the JavaScriptPrimitiveConverter Deserialize override for instance like this

public override object Deserialize(object primitiveValue, Type type, JavaScriptSerializer serializer)
{
    if (type == typeof(DateTime))
    {
        if (primitiveValue is string dateString
            && DateTime.TryParseExact(dateString, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var dateTime))
        {
            return dateTime;
        }
    }

    return null;
}

However the static JsonSettings class doesn't seem to be available in 2.0.0.

From searching it appears to me that there is some SimpleJson functionality that might be used to accomplish this, but I can't find any examples, and any documentation I find seems not to be updated with the 2.0.0 way to do things.

Upvotes: 0

Views: 952

Answers (2)

Nivin
Nivin

Reputation: 75

The question is about registering a PrimitiveConverter but the answer looks to be registering a JsonSerializer.

I was able to register a PrimitiveConverter by doing this in Global.Application_Start with Nancy 2.0.0:

protected void Application_Start(object sender, EventArgs e)
{
    Nancy.Json.JsonConfiguration.Default.PrimitiveConverters.Add(new CustomJavaScriptPrimitiveConverter());
}

Upvotes: 0

Ulf Åkerstedt
Ulf Åkerstedt

Reputation: 3236

Just as in previous 1.x versions you can use a custom JsonSerializer to instruct Nancy about general serialization/deserialization adjustments:

public sealed class CustomJsonSerializer : JsonSerializer
{
    public CustomJsonSerializer()
    {
        DateFormatString = "yyyy-MM-dd";
        // ... other formatting stuff ...
    }
}

And register this JsonSerializer with you container, for instance in the NancyBootStrapper's ConfigureApplicationContainer like this:

protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
    base.ConfigureApplicationContainer(container);
    container.Register<JsonSerializer, CustomJsonSerializer>();
    // ... other container setup ...
}

My problem was that I had missed including the Nancy.Serialization.JsonNet NuGet package, which is needed for this to work, for this specific project.

Upvotes: 4

Related Questions