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?

5
  • 3
    You're using =, which tests for equality (and then you're ignoreing the result). You want to use <- to set the property instead. Commented Mar 23, 2016 at 15:18
  • @kvb maybe I should make this a separate question. Why did F# go with = for comparison instead of ==? Commented Mar 23, 2016 at 15:20
  • 3
    If you find yourself using ignore, you're almost certainly doing something wrong. Commented Mar 23, 2016 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. Commented Mar 23, 2016 at 15:25
  • Ha! thanks. What a silly mistake. @kvb if you want to make that an answer I'll accept it. Commented Mar 23, 2016 at 15:26

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.