t3chb0t t3chb0t - 4 months ago 20
C# Question

How to handle array creation with custom JsonSerializerSettings?

I need to create some polymorphic types by using the

property in json so I added custom settings to the deserializer:

var jsonSerializerSetting = new JsonSerializerSettings
TypeNameHandling = TypeNameHandling.Auto

however now with the setting specified I cannot deserialize arrays anymore and something like this:

var arr = (string[])JsonConvert.DeserializeObject(@"[ 'foo' ]", jsonSerializerSetting);

ends with:

Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type

It fails even with the default
new JsonSerializerSettings()
. I guess it must be resetting something but I cannot figure out what.

Can I bring array/list etc creation back and still keep the ability to create the polimorphic types?

dbc dbc

The InvalidCastException you are seeing has nothing to do with TypeNameHandling.Auto. The problem is that you are not using the generic version of DeserializeObject(). You need to do:

var arr = JsonConvert.DeserializeObject<string []>(@"[ 'foo' ]", jsonSerializerSetting);

The non-generic JsonConvert.DeserializeObject(string, JsonSerializerSettings) you are using will indeed return a LINQ-to-JSON JArray which has no implicit or explicit cast to string [].