CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
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/76105021/sort-arrays-within-a-json-object-by-date-without-deserializing-the-object
class TestClass
{
public static void Test()
{
var json = GetJson();
var text1 = TestOriginal(json);
Console.WriteLine();
Console.WriteLine(text1);
var elapsed0 = Time(() => TestOriginal(json), 1);
Console.WriteLine("Time for {0} repetitions of original code: {1}", 1, elapsed0);
int count = 10000;
var elapsed1 = Time(() => TestOriginal(json), count);
var elapsed2 = Time(() => TestOriginalWithNoSort(json), count);
Console.WriteLine("Average time per repetition for {0} reps of original code: {1:0.0000} ms.", count, elapsed1.TotalMilliseconds/((double)count));
Console.WriteLine("Average time per repetition for {0} reps of original code without sorting: {1:0.0000} ms ({2:0.00}% faster).", count, elapsed2.TotalMilliseconds/((double)count), 100.0*(elapsed1 - elapsed2)/elapsed1);
var settings = new JsonSerializerSettings
{
DateParseHandling = DateParseHandling.None,
};
var root = JsonConvert.DeserializeObject<JToken>(json, settings);
Console.WriteLine("\nCorrectly formatted JSON:");
Console.WriteLine(root);
}
static string TestOriginalWithNoSort(string json)
{
var root = JToken.Parse(json);
var jsonArray = (JArray)root["results"];
var jsonlBuilder = new StringBuilder();
var serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc });
using (var textWriter = new StringWriter(jsonlBuilder))
using (var jsonWriter = new JsonTextWriter(textWriter) { Formatting = Formatting.None })
{
foreach (var obj in jsonArray)
{
var employments = obj.SelectToken("examples");
#if false
if (employments.Count() > 1)
{
var b = employments.ToObject<JArray>().OrderBy(c => c.SelectToken("date").ToObject<DateTime>(serializer)); // ToObject<JArray>() will clone the array
var newEmploymentArray = new JArray(b); // new JArray(b) will clone the array items again.
obj["examples"].Replace(newEmploymentArray);
}
#endif
obj.WriteTo(jsonWriter);
jsonWriter.WriteWhitespace("\n");
}
}
return jsonlBuilder.ToString();
}
static string TestOriginal(string json)
{
var root = JToken.Parse(json);
var jsonArray = (JArray)root["results"];
var jsonlBuilder = new StringBuilder();
var serializer = JsonSerializer.CreateDefault(new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Utc });
using (var textWriter = new StringWriter(jsonlBuilder))
using (var jsonWriter = new JsonTextWriter(textWriter) { Formatting = Formatting.None })
{
foreach (var obj in jsonArray)
{
var employments = obj.SelectToken("examples");
if (employments.Count() > 1)
{
var b = employments.ToObject<JArray>().OrderBy(c => c.SelectToken("date").ToObject<DateTime>(serializer)); // ToObject<JArray>() will clone the array
var newEmploymentArray = new JArray(b); // new JArray(b) will clone the array items again.
obj["examples"].Replace(newEmploymentArray);
}
obj.WriteTo(jsonWriter);
jsonWriter.WriteWhitespace("\n");
}
}
return jsonlBuilder.ToString();
}
static TimeSpan Time(Action action, int count)
{
var stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
try
{
for (int i = 0; i < count; i++)
action();
}
finally
{
stopwatch.Stop();
}
return stopwatch.Elapsed;
}
static string GetJson() => @"
{
""results"": [
{
""id"": ""abc456"" ,
""groups"": [
{
""parent_group"": null,
""type"": ""D""
} ,
{
""parent_group"": null ,
""type"": ""DEPARTMENT""
}
] ,
""examples"": [
{
""id"": ""e13b1e97-31e3-46e6-9d8f-9776c52e5ce0"" ,
""date"": ""2020-05-10T00:00:00Z""
} ,
{
""id"": ""bd31d475-6137-4409-8d17-535f1bf94071"" ,
""date"": ""2021-05-11T00:00:00Z""
} ,
{
""id"": ""0e0806ba-56f6-4527-8fd7-7e0061e30783"",
""date"": ""2019-05-11T00:00:00Z""
}
]
},
{
""id"": ""def456"" ,
""groups"": [
{
""parent_group"": null ,
""type"": ""D""
} ,
{
""parent_group"": null ,
""type"": ""D""
}
] ,
""examples"": [
{
""id"": ""e13b1e97-31e3-46e6-9d8f-9776c52e5ce0"" ,
""date"": ""2020-05-10T00:00:00Z""
} ,
{
""id"": ""bd31d475-6137-4409-8d17-535f1bf94071"" ,
""date"": ""2021-05-11T00:00:00Z""
} ,
{
""id"": ""0e0806ba-56f6-4527-8fd7-7e0061e30783"",
""date"": ""2019-05-11T00:00:00Z""
}
]
}
]
}
";
}
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;
}
}
}