-
Notifications
You must be signed in to change notification settings - Fork 266
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add F# compatible json serializer #609
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
<Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
||
<PropertyGroup> | ||
<OutputType>Exe</OutputType> | ||
<TargetFramework>net8.0</TargetFramework> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<Compile Include="Program.fs" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="../../src/Giraffe/Giraffe.fsproj" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> | ||
</ItemGroup> | ||
|
||
</Project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
open Microsoft.AspNetCore.Builder | ||
open Microsoft.AspNetCore.Http | ||
open Microsoft.Extensions.DependencyInjection | ||
open Microsoft.Extensions.Hosting | ||
open Giraffe | ||
open Giraffe.EndpointRouting | ||
open Newtonsoft.Json | ||
|
||
[<RequireQualifiedAccess>] | ||
module NewtonsoftJson = | ||
open System.IO | ||
open System.Text | ||
open System.Threading.Tasks | ||
open Microsoft.IO | ||
open Newtonsoft.Json.Serialization | ||
|
||
type Serializer(settings: JsonSerializerSettings, rmsManager: RecyclableMemoryStreamManager) = | ||
let serializer = JsonSerializer.Create settings | ||
let utf8EncodingWithoutBom = UTF8Encoding(false) | ||
|
||
static member DefaultSettings = | ||
JsonSerializerSettings(ContractResolver = CamelCasePropertyNamesContractResolver()) | ||
|
||
interface Json.ISerializer with | ||
member __.SerializeToString(x: 'T) = | ||
JsonConvert.SerializeObject(x, settings) | ||
|
||
member __.SerializeToBytes(x: 'T) = | ||
JsonConvert.SerializeObject(x, settings) |> Encoding.UTF8.GetBytes | ||
|
||
member __.SerializeToStreamAsync (x: 'T) (stream: Stream) = | ||
task { | ||
use memoryStream = rmsManager.GetStream("giraffe-json-serialize-to-stream") | ||
use streamWriter = new StreamWriter(memoryStream, utf8EncodingWithoutBom) | ||
use jsonTextWriter = new JsonTextWriter(streamWriter) | ||
serializer.Serialize(jsonTextWriter, x) | ||
jsonTextWriter.Flush() | ||
memoryStream.Seek(0L, SeekOrigin.Begin) |> ignore | ||
do! memoryStream.CopyToAsync(stream, 65536) | ||
} | ||
:> Task | ||
|
||
member __.Deserialize<'T>(json: string) = | ||
JsonConvert.DeserializeObject<'T>(json, settings) | ||
|
||
member __.Deserialize<'T>(bytes: byte array) = | ||
let json = Encoding.UTF8.GetString bytes | ||
JsonConvert.DeserializeObject<'T>(json, settings) | ||
|
||
member __.DeserializeAsync<'T>(stream: Stream) = | ||
task { | ||
use memoryStream = rmsManager.GetStream("giraffe-json-deserialize") | ||
do! stream.CopyToAsync(memoryStream) | ||
memoryStream.Seek(0L, SeekOrigin.Begin) |> ignore | ||
use streamReader = new StreamReader(memoryStream) | ||
use jsonTextReader = new JsonTextReader(streamReader) | ||
return serializer.Deserialize<'T>(jsonTextReader) | ||
} | ||
|
||
type JsonResponse = { Foo: string; Bar: string; Age: int } | ||
|
||
let endpoints: Endpoint list = | ||
[ GET [ route "/json" (json { Foo = "john"; Bar = "doe"; Age = 30 }) ] ] | ||
|
||
let notFoundHandler = "Not Found" |> text |> RequestErrors.notFound | ||
|
||
let configureServices (services: IServiceCollection) = | ||
services | ||
.AddSingleton<Json.ISerializer>(fun serviceProvider -> | ||
NewtonsoftJson.Serializer( | ||
JsonSerializerSettings(), | ||
serviceProvider.GetService<Microsoft.IO.RecyclableMemoryStreamManager>() | ||
) | ||
:> Json.ISerializer) | ||
.AddRouting() | ||
.AddResponseCaching() | ||
.AddGiraffe() | ||
|> ignore | ||
|
||
let configureApp (appBuilder: IApplicationBuilder) = | ||
appBuilder | ||
.UseRouting() | ||
.UseResponseCaching() | ||
.UseEndpoints(fun e -> e.MapGiraffeEndpoints(endpoints)) | ||
.UseGiraffe(notFoundHandler) | ||
|
||
[<EntryPoint>] | ||
let main (args: string array) : int = | ||
let builder = WebApplication.CreateBuilder(args) | ||
configureServices builder.Services | ||
|
||
let app = builder.Build() | ||
|
||
configureApp app | ||
app.Run() | ||
|
||
0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is also second way - just use the
recyclableMemoryStreamManager
constant:There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do you know if this other approach does provide some improvement compared to the one mentioned at this PR? Just curiosity due to this usage of Lazy<'T> and RecyclableMemoryStreamManager.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe not important one, but as
Lazy<RecyclableMemoryStreamManager>()
was the default, it was one argument less in code. :)Just started using
Giraffe
andOpenApi
and you guys are doing great work with those 🎉 👍There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Got it, thanks for the feedback 🚀