Getting json from types

The FSharp.Data.JsonProvider provides a means to go from json to an F# type. Is it possible to go in the reverse direction ie 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")

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

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.

链接地址: http://www.djcxy.com/p/19414.html

上一篇: Python:多任务与个人分配速度

下一篇: 从类型获取json