I have a JSON object which looks like
{
"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"
}
]
}
]
}
I have to sort the items in the example arrays in the result object and return them in JSON line format.
The solution I have right now iterates every array in the results object and sorts the example array by date, and replaces
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));
var newEmploymentArray = new JArray(b);
obj["examples"].Replace(newEmploymentArray);
}
obj.WriteTo(jsonWriter);
jsonWriter.WriteWhitespace("\n");
}
}
This is not performing well. It takes about 6ms without the code in the if (employments.Count() > 1)
block and 30ms with the if block. Is there a better way to do this?