FSharp.Data.JsonProvider - Getting json from types

2020-08-26 10:38发布

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

2条回答
劫难
2楼-- · 2020-08-26 11:25

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.

查看更多
Evening l夕情丶
3楼-- · 2020-08-26 11:28

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")
查看更多
登录 后发表回答