gpt-4-0314· OpenAI
WildChat-4.8M (AI2)
please provide me C# code that converts JsonElement to object. This function should…
- User
please provide me C# code that converts JsonElement to object. This function should check JsonElement ValueKind property and return JsonElement value via GetString(), GetDecimal() and other methods
- Assistant
using System; using System.Text.Json; public static class JsonElementToObjectConverter { public static object ConvertJsonElementToObject(JsonElement element) { switch (element.ValueKind) { case JsonValueKind.String: return element.GetString(); case JsonValueKind.Number: if (element.TryGetInt32(out int intValue)) return intValue; if (element.TryGetSingle(out float floatValue)) return floatValue; if (element.TryGetDouble(out double doubleValue)) return doubleValue; if (element.TryGetDecimal(out decimal decimalValue)) return decimalValue; break; case JsonValueKind.True: case JsonValueKind.False: return element.GetBoolean(); case JsonValueKind.Array: var arrayValues = new object[element.GetArrayLength()]; int index = 0; foreach (JsonElement arrayElement in element.EnumerateArray()) { arrayValues[index++] = ConvertJsonElementToObject(arrayElement); } return arrayValues; case JsonValueKind.Object: var dictionary = new Dictionary<string, object>(); foreach (JsonProperty property in element.EnumerateObject()) { dictionary[property.Name] = ConvertJsonElementToObject(property.Value); } return dictionary; case JsonValueKind.Null: return null; default: throw new ArgumentException($"Unknown JsonValueKind: {element.ValueKind}"); } throw new InvalidOperationException($"Cannot convert JsonElement with ValueKind: {element.ValueKind}"); } }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.