The problem is that your
channels
array contains a mixture of strings and objects. Javascript doesn't have a problem with that, because it's loosely-typed. But C# is a strongly-typed language, and doesn't have a native representation of something that can be either one type or another.
You could potentially use
LINQ to JSON[
^] to access the data in a loosely-typed manner.
Otherwise, you're going to need a
JsonConverter
. For example:
public class ChannelData
{
public string Insert { get; set; }
public string[] RepeatFor { get; set; }
public string ChannelOrder { get; set; }
public string[] TemplateChannels { get; set; }
}
[JsonConverter(typeof(ChannelConverter))]
public class Channel
{
public string Value { get; set; }
public ChannelData Data { get; set; }
}
public class ChannelConverter : JsonConverter
{
public override bool CanRead => true;
public override bool CanWrite => true;
public override bool CanConvert(Type objectType) => objectType == typeof(Channel);
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
switch (token.Type)
{
case JTokenType.Null:
{
return null;
}
case JTokenType.String:
{
return new Channel { Value = (string)token };
}
case JTokenType.Object:
{
return new Channel { Data = token.ToObject<ChannelData>() };
}
default:
{
throw new NotSupportedException();
}
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
switch (value)
{
case null:
{
writer.WriteNull();
break;
}
case Channel c when c.Value is string s:
{
writer.WriteValue(s);
break;
}
case Channel c when c.Data is ChannelData data:
{
serializer.Serialize(writer, data);
break;
}
case Channel:
{
writer.WriteNull();
break;
}
default:
{
throw new NotSupportedException();
}
}
}
}
public class Fixture
{
public string Name { get; set; }
public Channel[] Channels { get; set; }
}
With that in place, your sample JSON will deserialize correctly to a
Fixture
object. You can also reserialize it to produce the same output.