9

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")
jruizaranguren
  • 12,679
  • 7
  • 55
  • 73
Ian Spratt
  • 261
  • 2
  • 5
  • 2
    When I asked the creators back in September 2013, the answer was *no*: https://twitter.com/ploeh/status/382481359551594496 – Mark Seemann Mar 09 '14 at 09:21
  • `DataContractJsonSerializer`? http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer(v=vs.110).aspx – ildjarn Mar 09 '14 at 17:38

2 Answers2

5

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")
Gustavo Guerra
  • 5,319
  • 24
  • 42
-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.

Community
  • 1
  • 1
Fsharp Pete
  • 741
  • 4
  • 16
  • I guess the point of TP is you dont need to have that class written down, it is generated on the fly.. – nicolas Mar 12 '14 at 10:11
  • 1
    @nicolas I'm not sure I agree, since the asker wants to assign values to the TP class, it would need to be recorded 'somewhere' (the JSON file is 'somewhere'). I think a class definition is clearer than a JSON file. – Fsharp Pete Mar 12 '14 at 12:41
  • my point is that a TP's purpose is, as I understand it, to not have any intermediate class. that is irrespective of your use of the generated type (mutate, write, send over the wire etc...) – nicolas Mar 12 '14 at 16:29
  • While that may be true Pete, that doesn't help the poster with his/her problem. They wanted to know how to do something in F#. – super_J Jul 02 '16 at 12:31
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/13349844) – the Tin Man Aug 16 '16 at 23:05