1

I have a schema definition like that:

{
  "value": number | number[]
}

So I define a C# model like:

class Example
{
    public int[] Value { get; set; }
}

So I want a custom serializer that can be simplify a single element array and deserialize a single value to C# array.

Excepted test case:

var model = new Example { Value = new [] { 1 } };
var json = myCustomSerializer.Serialize(model);
Assert.Equal(json, "{\"value\":1}");
var json = "{\"value\":1}";
var model = myCustomSerializer.Deserialize<Example>(json);
Assert.SequenceEqual(model.Value, new [] { 1 });
var model = new Example { Value = new [] { 1, 2, 3 } };
var json = myCustomSerializer.Serialize(model);
Assert.Equal(json, "{\"value\":[1,2,3]}");
var json = "{\"value\":[1,2,3]}";
var model = myCustomSerializer.Deserialize<Example>(json);
Assert.SequenceEqual(model.Value, new [] { 1, 2, 3 });
PM Extra
  • 427
  • 4
  • 17
  • 1
    Could you share your attempted code so that we could help you better ? – Anu Viswan Jan 03 '20 at 07:52
  • 1
    This looks to be *mostly* a duplicate of [How to handle both a single item and an array for the same property using JSON.net](https://stackoverflow.com/q/18994685/3744182). The main difference is that you are deserializing to an array `T []` while the question there is deserializing to a list `List`. Can you adapt the converters there to your needs and/or switch to `List`, or do you still need help? – dbc Jan 03 '20 at 07:57
  • 1
    @dbc Thank you! I'm sorry for that I've searched relative question but I haven't found it. It's the exactly answer I want. I've marked this question duplicate. – PM Extra Jan 03 '20 at 08:00

0 Answers0