CSharp · Console
//https://stackoverflow.com/questions/65304693/jobject-tostring-formatting-issue-for-list
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Collections.ObjectModel;
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/65304693/jobject-tostring-formatting-issue-for-list
public static partial class JsonExtensions
{
public static string ToFormattedString(this JToken token, params JsonConverter[] converters)
{
if (token == null)
throw new ArgumentNullException();
using (var sw = new StringWriter(CultureInfo.InvariantCulture))
{
using (var jw = new JsonTextWriter(sw) { Formatting = Formatting.Indented })
FormattedWriteTo(token, jw, 0, converters);
return sw.ToString();
}
}
static void FormattedWriteTo(JToken token, JsonTextWriter writer, int depth, params JsonConverter[] converters)
{
if (token == null)
{
writer.WriteNull();
}
else if (token is JObject obj)
{
IList<JToken> asList = obj;
writer.WriteStartObject();
for (int i = 0, n = asList.Count; i < n; i++)
FormattedWriteTo(asList[i], writer, depth+1, converters);
writer.WriteEndObject();
}
else if (token is JArray array)
{
// Disable formatting for arrays.
// You could smarten this up further by e.g. checking to see whether the array contents are all primitive JValue tokens.
var old = writer.Formatting;
// The question requires an extra space between the property name and the array value.
if (depth > 0 && old == Formatting.Indented)
writer.WriteWhitespace(" ");
writer.Formatting = Formatting.None;
writer.WriteStartArray();
for (int i = 0, n = array.Count; i < n; i++)
FormattedWriteTo(array[i], writer, depth+1, converters);
writer.WriteEndArray();
writer.Formatting = old;
}
else if (token is JProperty property)
{
writer.WritePropertyName(property.Name);
FormattedWriteTo(property.Value, writer, depth+1, converters);
}
else
{
// JValue, JRaw, JConstructor
token.WriteTo(writer);
}
}
}
class TestClass
{
public static void Test()
{
var myObj = new
{
Vector = new List<int>{
1,2,3,4,5
}
};
Console.WriteLine(JToken.FromObject(myObj).ToFormattedString());
Assert.IsTrue(JToken.FromObject(myObj).ToFormattedString() == GetRequiredJson());
var myObj2 = new
{
Dates = new [] { new [] { new DateTime(2020, 12, 16) }, new [] { new DateTime(2020, 12, 17) }},
Data = new
{
Vector = new List<int>{
1,2,3,4,5
},
}
};
Console.WriteLine(JToken.FromObject(myObj2).ToFormattedString());
}
static string GetRequiredJson() => @"{
""Vector"": [1,2,3,4,5]
}";
}
public class Program
{
public static void Main()
{
Console.WriteLine("Environment version: {0} ({1})", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , GetNetCoreVersion());
Console.WriteLine("{0} version: {1}", typeof(JsonSerializer).Assembly.GetName().Name, typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine();
try
{
TestClass.Test();
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
}
public static string GetNetCoreVersion()
{
//https://techblog.dorogin.com/how-to-detect-net-core-version-in-runtime-ecd65ad695be
//
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.Location.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];
return null;
}
}