JsonProvider可以反序列化为通用字典吗? [英] Can JsonProvider deserialise to a Generic.Dictionary?

查看:51
本文介绍了JsonProvider可以反序列化为通用字典吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习类型提供程序,它看起来像一个突破性的功能.但是,我无法使用JsonProvider反序列化json,以便目标类型具有Generic.Dictionary属性.可以使用Json.NET完成.这是代码:

I'm learning about type providers and it looks like a ground breaking feature. However, I can't manage to deserialise json with JsonProvider so that the target type has a Generic.Dictionary property. It can be done with Json.NET. Here is the code:

type ByProv = JsonProvider<"""{"dict":{"A":1,"B":2}}""">
type ByHand(d:Dictionary<string,int>) =
    member val dict = d with get,set

let text = """{"dict":{"C":3,"D":4}}"""
let newt = JsonConvert.DeserializeObject<ByHand> text
let prov = ByProv.Parse text
printfn "%A" newt.dict.["C"]
//Can only call statically inferred A or B (and it will throw at run-time)
printfn "%A" prov.Dict.A

显然,默认情况下, dict 被推断为记录类型,而不是 Dictionary .可以覆盖吗?

Apparently, dict is inferred to be a record type and not a Dictionary by default. Can this be overriden?

推荐答案

JSON类型提供程序假定JSON记录用于存储记录(具有固定的字段名),并且JSON数组用于存储集合.您的示例就是其中一种情况并非如此出色的情况之一.

The JSON type provider assumes that JSON records are used for storing records (with fixed field names) and that JSON arrays are used for storing collections. Your example is one of the cases where this does not work all that great.

当您需要访问具有动态命名字段的JSON记录时,可以使用提供的类型公开的基础 JsonValue :

When you need to access a JSON record which has dynamically named fields, you can use the underlying JsonValue that is exposed by the provided type:

type ByProv = JsonProvider<"""{"dict":{"A":1,"B":2}}""">

let text = """{"dict":{"C":3,"D":4}}"""
let prov = ByProv.Parse text

prov.Dict.JsonValue.["C"].AsInteger()

这不是很好,我想可以将JSON类型提供程序扩展为更好地处理(并使记录更像数组).随时提交问题进行讨论和讨论;也许向 GitHub上的F#数据提交拉取请求!

This is not as nice and I suppose the JSON type provider could be extended to handle this better (and treat records more like arrays). Feel free to submit an issue for discussion & perhaps submit a pull request to F# Data on GitHub!

这篇关于JsonProvider可以反序列化为通用字典吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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