| | | 1 | | using System.Diagnostics.CodeAnalysis; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | using System.Text.Json.Nodes; |
| | | 4 | | using Jint; |
| | | 5 | | using Jint.Native; |
| | | 6 | | using Jint.Runtime.Interop; |
| | | 7 | | |
| | | 8 | | namespace Elsa.Expressions.JavaScript.ObjectConverters; |
| | | 9 | | |
| | | 10 | | internal class JsonElementConverter : IObjectConverter |
| | | 11 | | { |
| | | 12 | | public bool TryConvert(Engine engine, object value, [NotNullWhen(true)] out JsValue? result) |
| | | 13 | | { |
| | 6569 | 14 | | if (value is JsonElement jsonElement) |
| | | 15 | | { |
| | 9 | 16 | | result = ConvertJsonElementToJsValue(engine, jsonElement); |
| | 9 | 17 | | return true; |
| | | 18 | | } |
| | | 19 | | |
| | 6560 | 20 | | result = JsValue.Null; |
| | 6560 | 21 | | return false; |
| | | 22 | | } |
| | | 23 | | |
| | | 24 | | private static JsValue ConvertJsonElementToJsValue(Engine engine, JsonElement element) => |
| | 9 | 25 | | element.ValueKind switch |
| | 9 | 26 | | { |
| | 6 | 27 | | JsonValueKind.Object => JsValue.FromObject(engine, JsonObject.Create(element)), |
| | 1 | 28 | | JsonValueKind.Array => JsValue.FromObject(engine, JsonArray.Create(element)), |
| | 1 | 29 | | JsonValueKind.String => JsValue.FromObject(engine, element.GetString()), |
| | 0 | 30 | | JsonValueKind.Number => element.TryGetInt32(out var intValue) ? JsNumber.Create(intValue) : JsNumber.Create( |
| | 0 | 31 | | JsonValueKind.True => JsBoolean.True, |
| | 1 | 32 | | JsonValueKind.False => JsBoolean.False, |
| | 0 | 33 | | JsonValueKind.Undefined => JsValue.Undefined, |
| | 0 | 34 | | JsonValueKind.Null => JsValue.Null, |
| | 0 | 35 | | _ => throw new InvalidOperationException($"Unsupported JsonValueKind: {element.ValueKind}") |
| | 9 | 36 | | }; |
| | | 37 | | } |