3

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi @Tomas - I appreciate your answer (already accepted), but, I'm running into a minor problem. The reader I am creating is somewhat generic - the problem is defined by the user. Is there a way to iterate through the various properties and objects using your method (enumerate over them, generically)? I can't seem to find a way to do that. (I don't know what the fields will be beforehand - all I know is that it will be a tree structure).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.