F#, Json.NET 6.0 and WebApi - serialization of record types

前端 未结 2 1891
南旧
南旧 2020-12-03 14:49

Json.NET 6.0.1 adds F# support for records and discriminated unions. When serializing a F# record type using Json.NET I now get nicely formatted JSON.

The serializat

相关标签:
2条回答
  • 2020-12-03 15:19

    I believe it's because the backing fields that are emitted by F# records don't follow the same naming convention as C# property backing fields.

    The easiest way I've found to get around this is to change the ContractResolver at the startup of your web application from the System.Net.Http.Formatting.JsonContractResolver to use the Newtonsoft.Json.Serialization.DefaultContractResolver instead: -

    Formatters.JsonFormatter.SerializerSettings.ContractResolver <- DefaultContractResolver()
    

    You'll then get all JSON formatting done via Newtonsoft's JSON formatter rather than the NET one.

    0 讨论(0)
  • 2020-12-03 15:23

    You can adorn your records with the [<CLIMutable>] attribute:

    [<CLIMutable>]
    type MyDtr = {
        Message : string
        Time : string }
    

    That's what I do.


    For nice XML formatting, you can use:

    GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer <- true
    

    For nice JSON formatting, you can use:

    config.Formatters.JsonFormatter.SerializerSettings.ContractResolver <-
        Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
    
    0 讨论(0)
提交回复
热议问题