2

Newtonsoft's Json library has the ability to set global settings to apply custom converters and other settings. I've got a custom converter that works as long as I call it explicitly for each object I serialize, but I would like to set it globally so I don't have to do that. This can be done as shown here in C#:

https://stackoverflow.com/a/19121653/2506634

And the official signature of the DefaultSettings property is:

public static Func<JsonSerializerSettings> DefaultSettings { get; set; }

I've tried to translate this to F# like so:

JsonConvert.DefaultSettings = 
  System.Func<JsonSerializerSettings>
  (fun () ->           
    let settings = new JsonSerializerSettings()
    settings.Formatting <- Formatting.Indented
    settings.Converters.Add(new DuConverter())
    settings       
  )
  |> ignore

This compiles, and executes without error, but the custom converter is not applied when serializing. Also, for some reason setting the property returns a boolean (hence the |> ignore ) and I've noted that this boolean is false.

So, is something wrong with my translation to F#? Or is Newtonsoft perhaps ignoring my custom converter because the built in converter is being applied with precedence?

Community
  • 1
  • 1
jackmott
  • 1,112
  • 8
  • 16
  • 3
    You're using `=`, which tests for equality (and then you're `ignore`ing the result). You want to use `<-` to set the property instead. – kvb Mar 23 '16 at 15:18
  • @kvb maybe I should make this a separate question. Why did F# go with `=` for comparison instead of `==`? – Guy Coder Mar 23 '16 at 15:20
  • 3
    If you find yourself using `ignore`, you're almost certainly doing something wrong. – Fyodor Soikin Mar 23 '16 at 15:21
  • @GuyCoder - When in doubt the answer is usually O'Caml compatibility. Logically I think that this particular choice also makes more sense - why should the = symbol be associated with mutation? But it does make the transition from C-style languages more difficult. – kvb Mar 23 '16 at 15:25
  • Ha! thanks. What a silly mistake. @kvb if you want to make that an answer I'll accept it. – jackmott Mar 23 '16 at 15:26

1 Answers1

3

As I said in the comments, you want to use the assignment operator (<-) instead of the equality operator (=). Note that once you do this, the compiler will also apply the delegate conversion for you automatically (and there's no result to ignore), so your code can just become:

JsonConvert.DefaultSettings <-
    fun () -> 
        let settings = new JsonSerializerSettings()
        settings.Formatting <- Formatting.Indented
        settings.Converters.Add(new DuConverter())
        settings       
kvb
  • 54,864
  • 2
  • 91
  • 133