将 F# 记录类型序列化为 JSON 包括每个属性后的“@"字符 [英] Serializing F# Record type to JSON includes '@' character after each property

查看:11
本文介绍了将 F# 记录类型序列化为 JSON 包括每个属性后的“@"字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DataContractJsonSerializer 为 F# 记录类型创建 JSON,在每个属性名称后包含@"字符.有谁知道是否有可能获得没有这个尾随符号的 JSON?

The DataContractJsonSerializer creates JSON for F# record types that includes the '@' character after each property name. Does anyone know if it is possible to get JSON that does not have this trailing at symbol?

{"heart_rate@":20,"latitude@":45.0,"longitude@":108.0,"name@":"Rambo"}

这是我用来输出这个样本的脚本

Here is the script I use to output this sample

#r "System.Xml"
#r "System.Runtime.Serialization"

open System.Text
open System.Runtime.Serialization.Json
open System.IO

type Update = {
    name: string;
    latitude: decimal;
    longitude: decimal;
    heart_rate: int}

let update = {name = "Rambo"; latitude = 45.0m; longitude = 108.0m; heart_rate = 20}

let serializer = new DataContractJsonSerializer( typeof<Update> )

let stream = new MemoryStream()
let data = serializer.WriteObject(stream, update)
let updateData = stream.ToArray()

let json = (Encoding.UTF8.GetString(updateData))

printfn "%s" json

推荐答案

尽管 Daniel 的解决方案可以正常工作,但必须为记录中的每个属性添加属性是相当乏味的.事实证明,Json.NET 开箱即用地生成了更具可读性的 JSON.对于我的应用程序,我不需要专门使用 DataContractSerializer,所以是 JSON.net!

Although Daniel's solution will work correctly, it is rather tedious to have to add attributes to every property in the record. It turns out that Json.NET produces more readable JSON out of the box. For my application I do not need to use the DataContractSerializer specifically, so JSON.net it is!

这篇关于将 F# 记录类型序列化为 JSON 包括每个属性后的“@"字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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