CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Nodes;
using Newtonsoft.Json.Linq;
using NUnit.Framework; // Throws NUnit.Framework.AssertionException
//https://stackoverflow.com/questions/66495660/net-5-0-signature-change-of-system-text-json-jsonserializer-deserialize
#nullable enable
class TestClass
{
public static void Test()
{
Test("myKey");
Console.WriteLine();
Test("myMissingKey");
}
static void Test(string myKey)
{
var newtonsoftString = TestNewtonsoft(GetJson(), myKey);
Console.WriteLine("Newtonsoft result for key {0}: {1}", myKey, newtonsoftString);
var systemString = QueryJson(GetJson(), myKey, true);
Console.WriteLine("System.Text.Json.Nodes result for key {0}: {1}", myKey, systemString);
var docString = QueryJsonWithJsonDocument(GetJson(), myKey, true);
Console.WriteLine("JsonDocument result for key {0}: {1}", myKey, docString);
Assert.AreEqual(newtonsoftString, QueryJson(GetJson(), myKey, true));
Assert.AreEqual(newtonsoftString, QueryJsonWithJsonDocument(GetJson(), myKey, true));
}
static string? QueryJson(string json, string myKey, bool addComma = false)
{
// Parse to a JsonNode and cast to JsonObject. An exception is thrown if not an object
var node = JsonNode.Parse(json)!.AsObject();
// Query the array of strings
var query = (node[myKey] as JsonArray)?.Select(i => i?.ToString().ToUpper());
if (query == null)
return null; // Return null if key not found as per original code
if (addComma)
query = query.Concat(new [] { "" });
// Join the string array into a single comma-separated string
return string.Join(',', query);
}
static string? QueryJsonWithJsonDocument(string json, string myKey, bool addComma = false)
{
// Parse to a JsonNode and cast to JsonObject. An exception is thrown if not an object
using var doc = JsonDocument.Parse(json);
// Query the array of strings
var query = doc.RootElement.Get(myKey)?.EnumerateArray().Select(e => e.GetString()?.ToUpper());
if (query == null)
return null; // Return null if key not found as per original code
if (addComma)
query = query.Concat(new [] { "" });
// Join the string array into a single comma-separated string
return string.Join(',', query);
}
static string TestNewtonsoft(string json, string myKey)
{
string myList = null!;
object jsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(object));
// Loop through the keys
foreach (var jsonList in ((Newtonsoft.Json.Linq.JObject)(jsonObject)))
{
if (jsonList.Key == myKey)
{
foreach (object o in (jsonList.Value.ToArray()))
{
myList += o.ToString().ToUpper() + ',';
}
}
}
return myList;
}
static string GetJson() => @"{""myKey"":[""fir"",""dsdsd""],""status"":""ok""}";
}
//https://stackoverflow.com/a/61561343/3744182
public static partial class JsonExtensions
{
public static JsonElement? Get(this JsonElement element, string name) =>
element.ValueKind != JsonValueKind.Null && element.ValueKind != JsonValueKind.Undefined && element.TryGetProperty(name, out var value)
? value : (JsonElement?)null;
}
public class Program
{
public static void Main()
{
Console.WriteLine("Environment version: {0} ({1}), {2}", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion);
Console.WriteLine("System.Text.Json version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
}