dotnet-websharper / core

WebSharper - Full-stack, functional, reactive web apps and microservices in F# and C#
https://websharper.com
Apache License 2.0
595 stars 50 forks source link

Extendibility for WebSharper.Json #1337

Closed Jand42 closed 1 year ago

Jand42 commented 1 year ago

To make WebSharper.Json.Encode/Decode (WebSharper.TypedJson from C#) functions be able to support custom de/serialization for your types, it should look for an EncodeJson/DecodeJson static method on the type.

This then can be used within WebSharper libs too, for example adding Json support for decimals, which are proxied in a separate optional WebSharper.MathJS.Extensions library.

Example:

type Vector2D(x: float, y: float) =
    member thix.X = x
    member this.Y = y
    member this.Length = sqrt(x * x + y * y)

    static member EncodeJson (v: Vector2D): obj = [| v.X, v.Y |]

    static member DecodeJson (o: obj): Vector2D = Vector2D((As<float[]> o)[0], (As<float[]> o)[1])

Note: if you use generics, you must mark your EncodeJson/DecodeJson methods with the Inline attribute and call WebSharper.Json functions to handle the generic pieces of data.