如何编译Fable.JsonConverter

How to compile Fable.JsonConverter

我想使用 Fable.JsonConverter。

我的测试代码(几乎复制thisFableJson.fs在下面,

module FableJson

open Newtonsoft.Json

// Always use the same instance of the converter
// as it will create a cache to improve performance
let private jsonConverter = Fable.JsonConverter() :> JsonConverter

// Serialization
let toJson value =
    JsonConvert.SerializeObject(value, [|jsonConverter|])

// Deserialization
let ofJson<'T> json =
    JsonConvert.DeserializeObject<'T>(json, [|jsonConverter|])

paket.dependencies文件添加了nuget Fable.JsonConverter

source https://nuget.org/api/v2
storage:none

clitool dotnet-fable
nuget Fable.Core
nuget Fable.Import.Browser
nuget Fable.JsonConverter
添加了

src/paket.references 文件 Fable.JsonConverter

dotnet-fable
Fable.Core
Fable.Import.Browser
Fable.JsonConverter

但是无法编译

~~~ snip ~~~
ERROR in ./src/FableJson.fs
d:/SRC/Repos/Fable/testJsonConverter/src/FableJson.fs(11,4): (11,57) error FABLE: Cannot find replacement for Newtonsoft.Json.JsonConvert::SerializeObject
 @ ./src/App.fs 6:0-48
 @ ./src/testJsonConverter.fsproj
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./src/testJsonConverter.fsproj

ERROR in ./src/FableJson.fs
d:/SRC/Repos/Fable/testJsonConverter/src/FableJson.fs(15,4): (15,62) error FABLE: Cannot find replacement for Newtonsoft.Json.JsonConvert::DeserializeObject
 @ ./src/App.fs 6:0-48
 @ ./src/testJsonConverter.fsproj
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./src/testJsonConverter.fsproj

ERROR in ./src/FableJson.fs
d:/SRC/Repos/Fable/testJsonConverter/src/FableJson.fs(7,28): (7,49) error FABLE: Cannot find replacement for Fable.JsonConverter::.ctor
 @ ./src/App.fs 6:0-48
 @ ./src/testJsonConverter.fsproj
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./src/testJsonConverter.fsproj

我该怎么办?

看这里:http://fable.io/docs/interacting.html#json-serialization

在客户端,您应该使用 Fable.Core.JsInterop 函数 toJsonofJson

Fable.JsonConverter 仅适用于服务器端。它使用 Newtonsoft.Json,这是一个 .NET 库,在浏览器中没有 运行。您遇到的编译错误是因为 Fable 不知道如何将 Newtonsoft.Json 函数调用转换为 JavaScript.

当您使用一种语言,它可以在一次 运行 中工作(例如 .NET)并且还可以编译成另一种语言(例如 JS),但您应该尽量保持清晰的心智模型,其中您的所有代码都是 运行ning,因此它可以访问什么。

已接受的答案不再有效。对于较新的寓言,我唯一能找到的是 Fable.Core.JS.JSON.stringify ,它调用浏览器的内置序列化程序。 还有 Fable.Core.JS.JSON.parse(x) 其中 returns obj.

@Maslow 是对的,我们删除了寓言 2 Fable.JsonConverter 以支持社区创建的库。

  • Thoth.Json 提供类似 Elm 的体验,您可以根据自己的喜好手动或自动解码 JSON。这个库还提供了一个很好的错误消息
  • Fable.SimpleJson 一个在 Fable 项目中解析和转换 JSON 的库

Thoth.Json 与 Thoth.Json.Net 相辅相成,允许您在后端使用相同的 API。

我认为 Fable.SimpleJson 也提供对后端的支持,但我不确定。

您可以使用 JavaScript 本机 API Fable.Core.JS.JSON.stringifyFable.Core.JS.JSON.parse(x) 但您必须使用 unbox/cast 来强制您的类型不安全且容易损坏的数据。