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

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

问题描述

<一个href=\"http://james.newtonking.com/archive/2014/02/01/json-net-6-0-release-1-%E2%80%93-jsonpath-and-f-support\">Json.NET 6.0.1 增加了对记录和识别联合F#的支持。当使用Json.NET序列化F#记录类型我现在得到很好的格式化的JSON。

序列化是如下完成的:

 让转换器= [| (新StringEnumConverter():GT; JsonConverter)|]
JsonConvert.SerializeObject(questionSet,Formatting.Indented,转换器)

然而,当我试图通过ASP.NET的WebAPI 5.0服务,用C#编写揭露我的F#类型,序列化的JSON包括所有属性的@ -sign盈。在@ -sign来自内部支持字段的记录类型(这曾经是一个已知的问题与Json.Net和F#)。

不过 - 因为我使用Json.NET的更新版本,不应该的结果是一样的调用JsonConvert当作为?或者是 JsonConvert 行为不同于 JsonTextWriter JsonTextReader <? / p>

据我可以从的WebAPI源读 JsonMediaTypeFormatter 告诉 JsonTextWriter JsonTextReader 所使用的WebAPI。


解决方案

您可以使用装饰你的记录[; CLIMutable&GT;&LT] 属性:

  [&LT; CLIMutable&GT;]
键入MyDtr = {
    消息:字符串
    时间:字符串}

这就是我做


有关XML好的格式,你可以使用:

  GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer&LT;  - 真

有关不错JSON格式,你可以使用:

  config.Formatters.JsonFormatter.SerializerSettings.ContractResolver&LT;  - 
    Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()

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 serialization is done as follow:

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

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#).

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?

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

解决方案

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()

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

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