From d29525263b19f541591e2783b81f6d381112653e Mon Sep 17 00:00:00 2001 From: Knicker Date: Mon, 26 May 2025 18:56:02 +0200 Subject: [PATCH] Fix JSONDemo.cs - Casting error Fix casting error "The binary operator Equal is not defined for the types 'System.Text.Json.JsonElement' and 'System.String'." --- demo/DemoApp/JSONDemo.cs | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/demo/DemoApp/JSONDemo.cs b/demo/DemoApp/JSONDemo.cs index d3b8897d..3089708a 100644 --- a/demo/DemoApp/JSONDemo.cs +++ b/demo/DemoApp/JSONDemo.cs @@ -11,6 +11,7 @@ namespace DemoApp { using System.Text.Json; + using System.Linq; public class JSONDemo { @@ -21,11 +22,9 @@ public void Run() var orderInfo = "{\"totalOrders\": 5,\"recurringItems\": 2}"; var telemetryInfo = "{\"noOfVisitsPerMonth\": 10,\"percentageOfBuyingToVisit\": 15}"; - - - dynamic input1 = JsonSerializer.Deserialize(basicInfo); - dynamic input2 = JsonSerializer.Deserialize(orderInfo); - dynamic input3 = JsonSerializer.Deserialize(telemetryInfo); + dynamic input1 = ConvertJsonToExpandoObject(basicInfo); + dynamic input2 = ConvertJsonToExpandoObject(orderInfo); + dynamic input3 = ConvertJsonToExpandoObject(telemetryInfo); var inputs = new dynamic[] { @@ -57,5 +56,31 @@ public void Run() Console.WriteLine(discountOffered); } - } + + public static ExpandoObject ConvertJsonToExpandoObject(string json) + { + using JsonDocument doc = JsonDocument.Parse(json); + return ParseElement(doc.RootElement); + } + + private static ExpandoObject ParseElement(JsonElement element) + { + var expando = new ExpandoObject() as IDictionary; + + foreach (var property in element.EnumerateObject()) + { + expando[property.Name] = property.Value.ValueKind switch + { + JsonValueKind.String => property.Value.GetString(), + JsonValueKInd.Number => property.Value.TryGetInt64(out var 1) ? 1 : property.Value.GetDouble(), + JsonValueKind.True => true, + JsonValueKind.False => false, + JsonValueKind.Object => ParseElement(property.Value), + JsonValueKind.Array => property.Value.EnumerateArray().Select(e => e.ToString()).ToList(), + _ => null + }; + } + + return (ExpandoObject)expando; + } }