using System.Collections;
using System.Collections.Generic;
using System.Text.Json.Serialization;
public static void Main()
MyItems myItems1 = new MyItems([1, 2, 3]);
JsonSerializerOptions options = new JsonSerializerOptions { };
options.Converters.Add(new MyItemsConverter());
string jsonStr = System.Text.Json.JsonSerializer.Serialize(myItems1);
MyItems? myItems2 = System.Text.Json.JsonSerializer.Deserialize<MyItems>(jsonStr, options);
Console.WriteLine(String.Join(',', myItems2));
public class MyItemsConverter : JsonConverter<MyItems>
public override MyItems Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
if (reader.TokenType != JsonTokenType.StartArray)
throw new JsonException();
var obj = new MyItems(JsonSerializer.Deserialize<IReadOnlyCollection<int>>(ref reader, options));
public override void Write(Utf8JsonWriter writer, MyItems value, JsonSerializerOptions options)
JsonSerializer.Serialize(writer, value);
public class MyItems : IReadOnlyCollection<int>
private readonly List<int> _items;
public MyItems(IReadOnlyCollection<int> items)
_items = items != null ? new List<int>(items) : new List<int>();
public int Count => _items.Count;
public IEnumerator<int> GetEnumerator()
return _items.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator()