0

When creating a custom JsonConverter and overriding the public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) is it valid to change some settings from that JsonSerializer serializer like:

// ...
serializer.TypeNameHandling = TypeNameHandling.All;
// ...

It seems a valid action because the serializer is of type JsonSerializer which suggest it's a copy from the original JsonSerializer.

jps
  • 20,041
  • 15
  • 75
  • 79
Stef Heyenrath
  • 9,335
  • 12
  • 66
  • 121
  • 2
    Are you using a global `JsonSerializer` for all serialization calls, or are you manufacturing one for each call? If you are using the same serializer for all calls across multiple threads, then you shouldn't touch the incoming `JsonSerializer` because it won't be thread-safe. That's why I recommend to manufacture serializers as required and never share them across threads, share your `JsonSerializerSettings` instead. (Modifying the serializer does not modify the settings from which it was created.) – dbc Sep 14 '21 at 17:49
  • 1
    To confirm we can check the reference code. [`JsonSerializerInternalWriter`](https://github.com/JamesNK/Newtonsoft.Json/blob/52e257ee57899296d81a868b32300f0b3cfeacbe/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs#L669) calls `WriteJson()` with a [`JsonSerializerProxy`](https://github.com/JamesNK/Newtonsoft.Json/blob/52e257ee57899296d81a868b32300f0b3cfeacbe/Src/Newtonsoft.Json/Serialization/JsonSerializerProxy.cs) -- but this class simply proxies the original `JsonSerializer`, and modifications to `TypeNameHandling` are proxied back to the original. – dbc Sep 14 '21 at 17:51
  • 1
    If you are not sharing a `JsonSerializer` across threads then you should restore the original value of `TypeNameHandling` before leaving `WriteJson()` e.g. as shown in [this answer](https://stackoverflow.com/a/32404249/3744182). – dbc Sep 14 '21 at 17:53
  • Does that answer your question? – dbc Sep 14 '21 at 17:55
  • I used the `CopyReaderForObject` method as defined in https://stackoverflow.com/a/59286262/255966 – Stef Heyenrath Sep 15 '21 at 15:02

0 Answers0