Thomas
Thomas

Reputation: 12107

Can't serialize records, in F#, with json.net

A very basic example:

type private test =
    {
        a : string
        b : string list
    }

let t = { a = "hello"; b = ["1"; "2"] }
let s = JsonConvert.SerializeObject(t)

This will produce an empty string.

I have seen that json.net supports F# and that there are a lot of posts related to enum types, etc but I'm not there yet: I'm trying to serialize something very simple.

Many posts point toward another json serializer project, called Chiron, but it was updated a year ago and they're still like:

We’re working on Guides and reference content for working with Chiron, so keep an eye on the Updates Is there something obvious I haven't seen?

So ideally, working with json.net would be better, especially since I'm used to it in C#

Upvotes: 1

Views: 338

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243041

The issue seems to be that Json.Net only serializes public fields of F# records. When you mark the record as private, all its fields also become private and those are ignored. The following works as expected for me:

type test =
    {
        a : string
        b : string list
    }

let t = { a = "hello"; b = ["1"; "2"] }
let s = JsonConvert.SerializeObject(t)

This produces the expected JSON:

{"a":"hello","b":["1","2"]}

Upvotes: 2

Related Questions