FSharp.Data.JsonProvider - Getting json from types

一笑奈何 提交于 2019-12-10 03:45:36

问题


The FSharp.Data.JsonProvider provides a means to go from json to an F# type. Is it possible to go in the reverse direction i.e. declare an instance of one of the types created by FSharp.Data.JsonProvider, set the field values to be what I need, and then get the equivalent json?

I've tried things like this,

type Simple = JsonProvider<""" { "name":"John", "age":94 } """>

let fred = Simple( 
            Age = 5, // no argument or settable property 'Age'
            Name = "Fred")

回答1:


The latest version of F# Data now supports this. See the last example in http://fsharp.github.io/FSharp.Data/library/JsonProvider.html.

Your example would be:

type Simple = JsonProvider<""" { "name":"John", "age":94 } """>
let fred = Simple.Root(age = 5, name = "Fred")



回答2:


This is one area where C# has an edge over F#, at least in Visual Studio. You can copy your JSON example code into the clipboard and in Visual Studio use the Edit -> Paste Special -> Paste JSON As Classes and it will create a class to match the JSON example. From there you can easily use the class in F#.

More details on paste special here

Hopefully a matching feature will come for F# soon too.



来源:https://stackoverflow.com/questions/22280155/fsharp-data-jsonprovider-getting-json-from-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!