在F#中,我正在使用JavascriptSerializer.DeserializeObject
来读取JSON文件。那给了我一个Dictionary<string, object>
,对于任何这样的值(在运行时可能是int
,string
,bool
等),我只知道这是一个对象。
我知道,对于我的输入,某些键将始终具有与之关联的某些类型,但是它需要一些相当难看的代码来进行翻译。例如:
// deserialize the text, casting to a dictionary
let parsed = ... :?> Dictionary<string, System.Object>
type MyValue =
| Scalar of string
| Array of string[]
// myValue may be either string or string[]
// convert to F# discriminated union of Scalar|Array
let myValue = match parsed.["myValue"] with
| :? (Object[]) as obj -> Array (obj |> Array.map (fun o -> o :?> string))
| obj -> Scalar (obj :?> string)
在仍使用JavascriptSerializer的情况下,有没有更清洁,可能更安全,更惯用的方式?