[英]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. 我试图在我的F#应用程序中构建一个树(通过一个有区别的联合类型)来一般地表示我的数据。 I researched what was available on the web and I have found things like the JavaScriptSerializer and the DataContractJsonSerializer .
我研究了网上可用的内容,我找到了像JavaScriptSerializer和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). 我基本上希望能够从流中读入并使用我从流中获得的数据填充ParameterTree(包括适当的父/子关系)。 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. 我认为最好的选择是使用一些更轻量级的库,它只是在某些.NET字典中为您提供解析后的键/值对,然后将数据转换为一个不错的F#区分联合。
The Json.NET library has a JObject.Parse
method which seems to be doing exactly that. Json.NET库有一个
JObject.Parse
方法,似乎正是这样做的。 Here is a C# example from their web site: 这是他们网站上的一个C#示例:
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. 将
JObject
和JArray
结构转换为union类型应该不会太困难。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.