Skip to content

Commit d8e7c81

Browse files
authored
Document how to use with Giraffe
1 parent 85ff4a5 commit d8e7c81

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

docs/Using.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,44 @@ type MyTestController() =
9292
{| value = msg.value + 1 |}
9393
```
9494

95+
## Using with Giraffe
96+
97+
To use FSharp.SystemTextJson in Giraffe (for example with the `json` function):
98+
99+
* With Giraffe 5.x or newer, add the following to your `configureServices` function:
100+
101+
```fsharp
102+
open System.Text.Json
103+
open System.Text.Json.Serialization
104+
open Giraffe.Serialization
105+
106+
let configureServices (services: IServiceCollection) =
107+
let jsonOptions = JsonSerializerOptions()
108+
jsonOptions.Converters.Add(JsonFSharpConverter())
109+
services.AddSingleton(jsonOptions) |> ignore
110+
services.AddSingleton<IJsonSerializer, SystemTextJsonSerializer>() |> ignore
111+
// ...
112+
```
113+
114+
* Giraffe 4.x or earlier doesn't have the above `SystemTextJsonSerializer`, so you need to implement it in your project:
115+
116+
```fsharp
117+
open System
118+
open System.Text.Json
119+
open Giraffe.Serialization
120+
121+
type SystemTextJsonSerializer(options: JsonSerializerOptions) =
122+
interface IJsonSerializer with
123+
member _.Deserialize<'T>(string: string) = JsonSerializer.Deserialize<'T>(string, options)
124+
member _.Deserialize<'T>(bytes: byte[]) = JsonSerializer.Deserialize<'T>(ReadOnlySpan bytes, options)
125+
member _.DeserializeAsync<'T>(stream) = JsonSerializer.DeserializeAsync<'T>(stream, options).AsTask()
126+
member _.SerializeToBytes<'T>(value: 'T) = JsonSerializer.SerializeToUtf8Bytes<'T>(value, options)
127+
member _.SerializeToStreamAsync<'T>(value: 'T) stream = JsonSerializer.SerializeAsync<'T>(stream, value, options)
128+
member _.SerializeToString<'T>(value: 'T) = JsonSerializer.Serialize<'T>(value, options)
129+
```
130+
131+
and then add the same code as for Giraffe 5.x in your `configureServices` function.
132+
95133
## Using with SignalR
96134
97135
To use F# types in SignalR hubs, add the following to your startup `ConfigureServices`:

0 commit comments

Comments
 (0)