Parsing JSON Using F# (not Serialization)

十年热恋 提交于 2019-12-23 18:32:58

问题


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:


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.



来源:https://stackoverflow.com/questions/6361610/parsing-json-using-f-not-serialization

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!