I have a User class that has a property Roles of type ISet<Role>, where Role is an enum type. In JSON I get an array for that property ("Roles":["Admin","User"], for example). How can I write a custom converter to convert this array into ISet collection?
I've tried to write this class:
class CustomStringToRoleConverter : JsonConverter<ISet<User.Role>> {
public override ISet<User.Role> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
return null;
}
public override void Write(Utf8JsonWriter writer, ISet<User.Role> roles, JsonSerializerOptions options) {
StringBuilder builder = new StringBuilder();
builder.Append(string.Join(",", roles.Select(role => role.ToString()).ToArray()));
writer.WriteStartArray();
writer.WriteStringValue(builder.ToString());
writer.WriteEndArray();
}
}
but I don't know what to do in Read method. How do I get the array from Utf8JsonReader? There is a GetString method, but it throws exception when I call it:
InvalidOperationException: Cannot get the value of a token type 'StartArray' as a string.
I am using System.Text and System.Text.Json.