Skip to content

Fix JSONDemo.cs - Casting error #672

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 31 additions & 6 deletions demo/DemoApp/JSONDemo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
namespace DemoApp
{
using System.Text.Json;
using System.Linq;

public class JSONDemo
{
Expand All @@ -21,11 +22,9 @@ public void Run()
var orderInfo = "{\"totalOrders\": 5,\"recurringItems\": 2}";
var telemetryInfo = "{\"noOfVisitsPerMonth\": 10,\"percentageOfBuyingToVisit\": 15}";



dynamic input1 = JsonSerializer.Deserialize<ExpandoObject>(basicInfo);
dynamic input2 = JsonSerializer.Deserialize<ExpandoObject>(orderInfo);
dynamic input3 = JsonSerializer.Deserialize<ExpandoObject>(telemetryInfo);
dynamic input1 = ConvertJsonToExpandoObject(basicInfo);
dynamic input2 = ConvertJsonToExpandoObject(orderInfo);
dynamic input3 = ConvertJsonToExpandoObject(telemetryInfo);

var inputs = new dynamic[]
{
Expand Down Expand Up @@ -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<string, object>;

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;
}
}