使用F#解析JSON(不是序列化) [英] Parsing JSON Using F# (not Serialization)

查看:141
本文介绍了使用F#解析JSON(不是序列化)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在F#应用程序中构建树(通过区分的联合类型)以一般性地表示我的数据.我研究了网络上的可用内容,发现了 JavaScriptSerializer DataContractJsonSerializer .问题是,我并没有真正将数据序列化为一个特定的对象.

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.

这是我受歧视的工会:

type ParameterTree =
    | End
    | Node of string * Dictionary<string, Parameter> * ParameterTree

我基本上希望能够从流中读取并用从流中获取的数据(包括适当的父/子关系)填充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.

推荐答案

我认为最好的选择是使用一些更轻量级的库,该库只为您提供一些.NET词典中已解析的键/值对,然后将其转换为数据发送到一个很好的F#区分的联合.

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.

Json.NET库具有JObject.Parse方法,该方法似乎可以正是这样做的.这是他们网站上的一个C#示例:

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];

JObjectJArray结构转换为并集类型应该不太困难.

It shouldn't be too difficult to convert JObject and JArray structures to your union type.

这篇关于使用F#解析JSON(不是序列化)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆