If you simply want to capture a collection inside a surrogate wrapper object, the easiest way to do so is to make the wrapper appear to be a read-only collection to Json.NET. To do that, you must:
- Implement
IEnumerable<T>
for some T
(here int
).
- Add a constructor that takes an
IEnumerable<T>
for the same T
. (From experimentation, a constructor that takes T []
is not sufficient.)
Thus if you define your ArrayWrapper
as follows:
public struct ArrayWrapper : IEnumerable<int>
{
private readonly int[] array;
public int Item0 { get { return array[ 0 ]; } }
public int Item1 { get { return array[ 1 ]; } }
public ArrayWrapper(int[] array) {
this.array = array;
}
public ArrayWrapper(IEnumerable<int> enumerable)
{
this.array = enumerable.ToArray();
}
public static implicit operator ArrayWrapper(int[] array) {
return new ArrayWrapper( array );
}
public IEnumerator<int> GetEnumerator()
{
return (array ?? Enumerable.Empty<int>()).GetEnumerator();
}
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
You will be able to serialize and deserialize Obj
into the following JSON:
{"Array":[[1,101]]}
Demo fiddle #1 here.
However, in comments you mention your array actually has a fixed schema as documented in Public Rest API for Binance: Kline/Candlestick data. If so, you could adopt the approach from this answer to C#: Parsing a non-JSON array-only api response to a class object with x properties which specifically addresses Binance Kline/Candlestick data:
I.e. for the specific model shown in your question, modify its definition as follows:
[JsonConverter(typeof(ObjectToArrayConverter<ArrayWrapper>))]
public struct ArrayWrapper
{
[JsonProperty(Order = 1)]
public int Item0 { get; set; }
[JsonProperty(Order = 2)]
public int Item1 { get; set; }
}
And you will be able to (de)serialize the same JSON. Note that the converter is entirely generic and can be reused any time the pattern of (de)serializing an array with a fixed schema into an object arises.
(You might also want to change the struct
to a class
since mutable structs are discouraged.)
Demo fiddles #2 here and #3 here showing the use of a JsonConverter
attribute applied to one of the serializable properties.