Search code examples
c#.netf#json.netrefit

How should I serialize JSON from Refit in an F# project?


I'm using Refit in a C# project to create an API client. I'd prefer to do everything with F# but Refit doesn't fully support F# yet.

If I create my User model in C# everything is fine but I'd prefer to be able to express which properties are optional and handle them appropriately.

If I add FSharp.Core and use FSharpOption<string> or similar then assertions that try to access those members fail with a NullReferenceException but only if the JSON response contains something optional.

If I create a separate F# project that contains a User model I always get a NullReferenceException when trying to deserialize.

Admittedly, keeping any models as part of the C# project seems easier but I don't want to sacrifice knowing which members are optional on the F# side.

What is the best way to go about this?


Solution

  • My current thinking is to leave the C# project as-is and create an F# wrapper which returns models in a Result type, with optional members where appropriate.


    Update:

    I ended up doing this and adding the following to my FSharp models:

    static member ToCSharp :
        user: User
           -> CSharp.User
    
    static member FromCSharp :
        user: CSharp.User
           -> User option