F#、Json.NET 6.0 和 WebApi - 记录类型的序列化 [英] F#, Json.NET 6.0 and WebApi - serialization of record types

查看:24
本文介绍了F#、Json.NET 6.0 和 WebApi - 记录类型的序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Json.NET 6.0.1 添加了对记录和可区分联合的 F# 支持.使用 Json.NET 序列化 F# 记录类型时,我现在可以得到格式良好的 JSON.

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.

序列化完成如下:

let converters = [| (new StringEnumConverter() :> JsonConverter) |]
JsonConvert.SerializeObject(questionSet, Formatting.Indented, converters)

但是,当我尝试通过用 C# 编写的 ASP.NET WebApi 5.0 服务公开我的 F# 类型时,序列化的 JSON 在所有属性前面包含一个 @-sign.@-sign 来自记录类型的内部支持字段(这曾经是 Json.Net 和 F# 的已知问题).

However, when I try to expose my F# types through a ASP.NET WebApi 5.0 service, written in C#, the serialized JSON includes an @-sign infront of all properties. The @-sign comes from the internal backing field for the record type (this used to be a known problem with Json.Net and F#).

但是 - 由于我使用的是 Json.NET 的更新版本,结果不应该与调用 JsonConvert 时的结果相同吗?还是 JsonConvertJsonTextWriterJsonTextReader 的行为不同?

But - since I'm using the updated version of Json.NET, shouldn't the result be the same as when calling JsonConvert? Or is JsonConvert behaving differently than JsonTextWriterand JsonTextReader?

据我阅读 WebApi 源代码中的 JsonMediaTypeFormatter 来看,JsonTextWriterJsonTextReader 被 WebApi 使用.

As far as I can tell from reading the JsonMediaTypeFormatter in the WebApi source JsonTextWriterand JsonTextReader is used by WebApi.

推荐答案

您可以使用 [<CLIMutable>] 属性装饰您的记录:

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

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

就是这样我愿意.

对于漂亮的 XML 格式,您可以使用:

For nice XML formatting, you can use:

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

对于漂亮的 JSON 格式,您可以使用:

For nice JSON formatting, you can use:

config.Formatters.JsonFormatter.SerializerSettings.ContractResolver <-
    Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()

这篇关于F#、Json.NET 6.0 和 WebApi - 记录类型的序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆