-
Notifications
You must be signed in to change notification settings - Fork 70
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: Use object type for option value and custom converter to restric…
…t invalid types (#13968)
- Loading branch information
Showing
4 changed files
with
126 additions
and
8 deletions.
There are no files selected for viewing
38 changes: 38 additions & 0 deletions
38
backend/src/Designer/Helpers/JsonConverterHelpers/OptionConverterHelper.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
using System; | ||
using System.Text.Json; | ||
using System.Text.Json.Serialization; | ||
|
||
namespace Altinn.Studio.Designer.Helpers.JsonConverterHelpers; | ||
|
||
public class OptionConverter : JsonConverter<object> | ||
{ | ||
public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | ||
{ | ||
return reader.TokenType switch | ||
{ | ||
JsonTokenType.String => reader.GetString(), | ||
JsonTokenType.Number when reader.TryGetDouble(out double d) => d, | ||
JsonTokenType.True => true, | ||
JsonTokenType.False => false, | ||
_ => throw new JsonException($"Unsupported JSON token for Option.Value: {reader.TokenType}") | ||
}; | ||
} | ||
|
||
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options) | ||
{ | ||
switch (value) | ||
{ | ||
case string s: | ||
writer.WriteStringValue(s); | ||
break; | ||
case double d: | ||
writer.WriteNumberValue(d); | ||
break; | ||
case bool b: | ||
writer.WriteBooleanValue(b); | ||
break; | ||
default: | ||
throw new JsonException("Unsupported type for Option.Value."); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters