JsonProvider "This is not a constant expression or valid custom attribute value"



给定代码:

#if INTERACTIVE
#r "binDebugFSharp.Data.dll"
#endif
open System
open FSharp.Data
open FSharp.Data.Json
let testJson = """{ "workingDir":"hello", "exportDir":"hi there", "items":[{ "source":"", "dest":"", "args": {"name":"that"} }] }"""
//here is where i get the error
let Schema = JsonProvider<testJson>

最后一行不断给我错误"这不是一个常量表达式或有效的自定义属性值"——这意味着什么?我如何让它读取这个JSON?

字符串必须标记为常量。为此,请使用[<Literal>]属性。此外,类型提供程序创建的是类型,而不是值,因此需要使用type而不是let:

open FSharp.Data
[<Literal>]
let testJson = """{ "workingDir":"hello", "exportDir":"hi there", "items":[{ "source":"", "dest":"", "args": {"name":"that"} }] }"""
type Schema = JsonProvider<testJson>

JsonProvider可以被视为在编译时专用的参数化JSON解析器(加上解析器生成的数据类型)。

您给它的参数(一个字符串或JSON文件的路径)定义了JSON数据的结构——如果您愿意,可以使用模式。这允许提供者创建一个类型,该类型将静态地具有JSON数据应该具有的所有属性,并且这些属性的集合(以及它们各自的类型)是用您提供给提供者的JSON样本定义的(实际上是从中推断的)。

因此,使用JsonProvider的正确方法显示在文档中的一个示例中:

// generate the type with a static Parse method with help of the type provider
type Simple = JsonProvider<""" { "name":"John", "age":94 } """>
// call the Parse method to parse a string and create an instance of your data
let simple = Simple.Parse(""" { "name":"Tomas", "age":4 } """)
simple.Age
simple.Name

这个例子就是从这里取的。

相关内容

最新更新