t3chb0t t3chb0t - 3 months ago 14
C# Question

How to handle array creation with custom JsonSerializerSettings?

I need to create some polymorphic types by using the

$type
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
'System.String[]'


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
Answer

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 [].