Reputation: 34632
I am trying to build a tree (via a discriminated union type) in my F# application to represent my data generically. I researched what was available on the web and I have found things like the JavaScriptSerializer and the DataContractJsonSerializer. The problem is, I am not really serializing the data into a specific object.
Here is my discriminated union:
type ParameterTree =
| End
| Node of string * Dictionary<string, Parameter> * ParameterTree
I basically want to be able to read in from a stream and populate the ParameterTree with the data I am getting from the stream (including appropriate parent/child relationship). I am stuck on where to begin with this. If anybody can point me in the right direction, I would appreciate it.
Upvotes: 3
Views: 1043
Reputation: 243041
I think that the best option would be to use some more lightweight library that simply gives you the parsed key/value pairs in some .NET dictionary and then transform the data to a nice F# discriminated union.
The Json.NET library has a JObject.Parse
method which seems to be doing exactly that. Here is a C# example from their web site:
JObject o = JObject.Parse(json);
string name = (string)o["Name"];
JArray sizes = (JArray)o["Sizes"];
string smallest = (string)sizes[0];
It shouldn't be too difficult to convert JObject
and JArray
structures to your union type.
Upvotes: 3