简体   繁体   中英

Parsing JSON Using F# (not Serialization)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM