How to format an existing json string in C#

Recently I had to find a way how to format or indent an existing json string in .NET Framework 4.8 using C#. My goal was to print the Json result of a web request on the console. But the response was not formatted so the output was very hard to read. I knew I could deserialize the response into an object and serialize it again with Formatting.Indented, but I had a feeling that this would not be the most performant way to do it.

I struggled a little bit to find a solution for the problem on the web. Here is the way to do it with the Newtonsoft.Json library:

var formattedJson = JToken.Parse(json).ToString(Formatting.Indented);

To prove my feelings right a created a small benchmark project that compares the two approaches. Here is the Benchmark class:

	public class FormatJsonBenchmark
		private const string UnformattedJson = "[{\"userId\":1,\"id\":1,\"title..." // cut for readabilty

		public void FormatWithJToken()
			var formattedJson = JToken.Parse(UnformattedJson).ToString(Formatting.Indented);

		public void FormatWithDeserializeAndSerialize()
			var obj = JsonConvert.DeserializeObject(UnformattedJson);
			var formattedJson = JsonConvert.SerializeObject(obj, Formatting.Indented);

I used the albums response from the public json placeholder api and removed the indentation for the test input.

Here are the results:

| Method                            | Mean     | Error   | StdDev  | Gen0     | Gen1    | Allocated |
|---------------------------------- |---------:|--------:|--------:|---------:|--------:|----------:|
| FormatWithJToken                  | 396.0 us | 7.05 us | 6.25 us | 181.1523 |  1.4648 | 147.37 KB |
| FormatWithDeserializeAndSerialize | 438.7 us | 5.32 us | 4.15 us | 127.4414 | 19.5313 | 138.41 KB |

As you can see, the difference is not that big. The JToken.Parse(json).ToString() method is roughly 10% faster and also allocates a little less memory. So I guess my feelings were right. But does the performance difference matter? In my scenario definitely not.

Leave a Comment

Your email address will not be published. Required fields are marked *