CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using NUnit.Framework; // Throws NUnit.Framework.AssertionException
//https://stackoverflow.com/questions/77834272/create-newtonsoft-json-linq-jarray-from-another-array-with-different-structure
class TestClass
{
public static void Test()
{
var jsonString = GetJson();
// Parse (or load from a stream) the incoming JSON as a JArray
var array = JArray.Parse(jsonString);
var query = array
.OfType<JObject>()
.Select(o =>
new JObject
{
{"Fields", new JArray(o.Properties().Select(p => new JObject{{"Key", p.Name}, {"Value", p.Value}}))},
});
var newArray = new JArray(query);
Console.WriteLine(newArray);
Assert.That(JToken.DeepEquals(JArray.Parse(GetRequiredJson()), newArray));
}
static string GetJson() =>
"""
[
{
"Relationship": "child",
"FirstName": "Alex"
}
]
""";
static string GetRequiredJson() =>
"""
[
{
"Fields": [
{
"Value": "child",
"Key": "Relationship"
},
{
"Value": "Alex",
"Key": "FirstName"
}
]
}
]
""";
}
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("{0} version: {1}", typeof(JsonSerializer).Namespace, typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
}