Can JsonProvider deserialise to a Generic.Dictionary?

安稳与你 提交于 2021-01-27 08:07:52

问题


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

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


回答1:


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.

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()

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!




回答2:


If you want to convert a JSON dictionary to a .net dictionary you can use the Properties() method, and the dict function, like this:

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

let text = """{"dict":{"C":3,"D":4}}"""

let prov = ByProv.Parse text

let d = prov.Dict.JsonValue.Properties() |> dict

the type of d is System.Collections.Generic.IDictionary<string,JsonValue>. If you want it to be integer you can use a Seq.map in the middle:

let d =
    prov.Dict.JsonValue.Properties()
    |> Seq.map (fun (k,v) -> k,v.AsInteger())
    |> dict


来源:https://stackoverflow.com/questions/24182737/can-jsonprovider-deserialise-to-a-generic-dictionary

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