I want to create an object with this interface in F#:
namespace JWT
{
/// <summary>
/// Provides JSON Serialize and Deserialize. Allows custom serializers used.
/// </summary>
public interface IJsonSerializer
{
/// <summary>
/// Serialize an object to JSON string
/// </summary>
/// <param name="obj">object</param>
/// <returns>JSON string</returns>
string Serialize(object obj);
/// <summary>
/// Deserialize a JSON string to typed object.
/// </summary>
/// <typeparam name="T">type of object</typeparam>
/// <param name="json">JSON string</param>
/// <returns>Strongly-typed object</returns>
T Deserialize<T>(string json);
}
}
I have tried using an object expression but the generic Deserialize method is tripping me up:
let serializer =
{
new JWT.IJsonSerializer
with
member this.Serialize (o : obj) =
failwith "Not implemented"
member this.Deserialize (json : string) =
let decoded : Result<'t, string> =
Decode.fromString payloadDecoder json
match decoded with
| Result.Ok (o : 't) ->
o
| Result.Error error ->
failwith error
}
The error is:
This code is not sufficiently generic. The type variable 'a could not be generalized because it would escape its scope
How can I implement this?
$ dotnet --version
3.1.300
Decode.fromStringis from Thoth.Jsonstring -> Decoder<'t> -> Result<'t, string>- sdgfsdh