|
| 1 | +// This file is part of CycloneDX Library for .NET |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the “License”); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an “AS IS” BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | +// |
| 15 | +// SPDX-License-Identifier: Apache-2.0 |
| 16 | +// Copyright (c) OWASP Foundation. All Rights Reserved. |
| 17 | + |
| 18 | +using System; |
| 19 | +using System.Diagnostics.Contracts; |
| 20 | +using System.Text.Json; |
| 21 | +using System.Text.Json.Serialization; |
| 22 | + |
| 23 | +namespace CycloneDX.Spdx.Serialization.Converters |
| 24 | +{ |
| 25 | + |
| 26 | + public class HyphenToUnderscoreEnumConverter<T> : JsonConverter<T> where T: struct |
| 27 | + { |
| 28 | + public override T Read( |
| 29 | + ref Utf8JsonReader reader, |
| 30 | + Type typeToConvert, |
| 31 | + JsonSerializerOptions options) |
| 32 | + { |
| 33 | + if (reader.TokenType == JsonTokenType.Null |
| 34 | + || reader.TokenType != JsonTokenType.String) |
| 35 | + { |
| 36 | + throw new JsonException(); |
| 37 | + } |
| 38 | + |
| 39 | + var enumString = reader.GetString(); |
| 40 | + |
| 41 | + T enumValue; |
| 42 | + var success = Enum.TryParse<T>(enumString.Replace("-", "_"), ignoreCase: true, out enumValue); |
| 43 | + if (success) |
| 44 | + { |
| 45 | + return enumValue; |
| 46 | + } |
| 47 | + else |
| 48 | + { |
| 49 | + throw new JsonException(); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + public override void Write( |
| 54 | + Utf8JsonWriter writer, |
| 55 | + T value, |
| 56 | + JsonSerializerOptions options) |
| 57 | + { |
| 58 | + Contract.Requires(writer != null); |
| 59 | + writer.WriteStringValue(value.ToString()); |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments