For a general purpose converter, here's an implementation that uses attributes to associate the properties:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class JsonArrayIndexAttribute : Attribute
{
public JsonArrayIndexAttribute(int index)
{
Index = index;
}
public int Index { get; }
}
public class JsonArrayConverter<T> : JsonConverter<T>
{
public override T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer)
{
switch (reader.TokenType)
{
case JsonToken.StartArray:
var members = GetIndexedMembers(objectType);
var arr = JArray.ReadFrom(reader);
var fromArray = hasExistingValue ? existingValue! : Activator.CreateInstance<T>()!;
foreach (var (member, value) in members.Zip(arr))
{
member.setter?.Invoke(fromArray, Convert.ChangeType(value, member.type));
}
return fromArray;
case JsonToken.StartObject:
var fromObject = hasExistingValue ? existingValue! : Activator.CreateInstance<T>()!;
serializer.Populate(reader, fromObject);
return fromObject;
case JsonToken.Null:
return default;
case JsonToken.Undefined:
return hasExistingValue ? existingValue : default;
default:
throw new JsonSerializationException($"Unexpected TokenType: {reader.TokenType}");
}
}
public override void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
var members = GetIndexedMembers(value.GetType());
writer.WriteStartArray();
foreach (var member in members)
{
writer.WriteValue(member.getter?.Invoke(value));
}
writer.WriteEndArray();
}
private IEnumerable<(Type? type, Func<object, object?>? getter, Action<object, object?>? setter)> GetIndexedMembers(Type type)
{
var indexedMembers =
(from member in type.GetMembers()
let index = (JsonArrayIndexAttribute?)member.GetCustomAttribute(typeof(JsonArrayIndexAttribute))
where index != null
select (member, index.Index))
.ToLookup(x => x.Index, x => x.member);
return
(from i in Enumerable.Range(0, indexedMembers.Max(x => x.Key) + 1)
from m in indexedMembers[i].TakeLast(1).DefaultIfEmpty()
select CreateAccessors(m));
(Type, Func<object, object?>?, Action<object, object?>?) CreateAccessors(MemberInfo m) => m switch
{
PropertyInfo p => (p.PropertyType, obj => p.GetValue(obj), (obj, value) => p.SetValue(obj, value)),
FieldInfo f => (f.FieldType, obj => f.GetValue(obj), (obj, value) => f.SetValue(obj, value)),
_ => default,
};
}
}
Then to use it in your case:
[JsonConverter(typeof(JsonArrayConverter<Person>))]
public class Person
{
[JsonArrayIndex(0)]
public string First { get; set; } = default!;
[JsonArrayIndex(1)]
public string Last { get; set; } = default!;
[JsonArrayIndex(2)]
public int Age { get; set; }
}