我正在解码不同类型的json对象流:
type AppRow =
| ZoneR of ZoneRow
| CustomerR of CustomerRow
我需要返回已解码的对象:
//None work:
let fromJson x =
let fromJson x:'T =
let fromJson<'T> x =
let fromJson<'T> x:'T =
Json.Compact.deserialize x
let decodeLog table json =
match table with
| "zone" ->
fromJson json |> ZoneR
| "customer" ->
fromJson json |> CustomerR
| _ -> failwith "Not ready yet"
我无法想象how replicate the effect of:
public static T deserialize<T> (string json)
{
return JsonConvert.DeserializeObject<T> (json, Compact.Internal.Settings.settings);
}
我不想打电话给Json.Compact.deserialize
因为我正在抽象编码/解码,需要在fromJson
答案 0 :(得分:2)
如果要定义一个接受字符串且具有泛型返回类型的函数,则以下两个中的任何一个都应该有效(后者允许您在调用函数时显式指定类型,前者不需要类型需要推断)。
let fromJson x : 'T = ...
let fromJson<'T> x : 'T = ...
您可以更明确地注释x
,以便明确:
let fromJson (x:string) : 'T = ...
当你说你的代码不起作用时,你究竟是什么意思?以下是一个简单的愚蠢示例,只处理两个值(而不是正确解码JSON),但编译得很好并显示语法:
type AppRow =
| ZoneR of int
| CustomerR of string
let fromJson (x:string) : 'T =
if x = "1" then unbox 1
elif x = "hi" then unbox "hi"
else failwith "wrong input"
let decodeLog table json =
match table with
| "zone" ->
fromJson json |> ZoneR
| "customer" ->
fromJson json |> CustomerR
| _ -> failwith "Not ready yet"
decodeLog "zone" "1"
decodeLog "customer" "hi"