Question

If I use the same settings across my project, can I instantiate a single static copy of my JsonSerializerSettings and use that throughout?

For example :

private static readonly JsonSerializerSettings settings = new JsonSerializerSettings {
    Formatting              = Formatting.Indented,
    TypeNameHandling        = TypeNameHandling.None,
    DateFormatHandling      = DateFormatHandling.IsoDateFormat,
    TypeNameAssemblyFormat  = FormatterAssemblyStyle.Simple
};

public static string ToJSONString(this Object source) {
    return JsonConvert.SerializeObject(source, settings);
}   

So, am i thread dangerous?

Was it helpful?

Solution

The following conversation happened on twitter, @JamesNK being the author of JSON.net: https://twitter.com/jonathan_oliver/status/332227095616966656

From: Jonathan Oliver ‏@jonathan_oliver To: @JamesNK

Are the static JsonConvert.DeserializeObject methods thread safe? Getting some strange errors using 5.0.4 and 5.0.5.

Response:

James Newton-King ♔ ‏@JamesNK 8 May 2013 @jonathan_oliver

Yes. Create an issue on GitHub if they’re not

Response:

Jonathan Oliver ‏@jonathan_oliver 9 May 2013

@JamesNK It turns out a ContractResolver attached to a static JsonSerializerSettings object I used with JsonConvert wasn't thread safe.

I do not see that a bug was ever filed, but this does hint that the design of them is supposed to be thread safe, but there maybe implementation specific ways to ruin that or it might not be as a whole.

OTHER TIPS

Since you say you don't mutate JsonSerializerSettings there is no need to worry about thread safety. Thread race can happen only when modifying the shared data in another thread but that is not the case here.

I suggest you to read this article, in the end you should have a good understanding of threads, thread safety etc.

Also Thread safety is a more general term, you need to be more precise what you meant by that. Refer What is this thing you call "thread safe"? for more info.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top