In my current project, I had to deal with huge JSON files, which contain the order and properties of our layout elements. For CSS styling purposes, I had to move one particular array item to the end, create a new object and move all existing elements inside of that new object. This was tedious work when I did that manually.
So I decided to develop a little C# Console application, taking care of that for me. After a few hours I managed to complete it – and here are my learnings.
I went for JSON.Net, which is the de-facto standard for .NET.
The problem with JSON is that you can get different types (array, object). Hence, we do not want to be too type-specific to be able to cast to the expected type. And we have the wonderful dynamic type declaration, which prevents compile-time type checks. So we use dynamic as long in the line as possible.
dynamic json = JsonConvert.DeserializeObject(jsonString) dynamic element = json.GetValue("Element");
Working with Elements
I found two techniques for selecting a particular element in the JSON tree. You can either use SelectToken, which works best for nested objects. Alternatively you can also use LINQ queries like FirstOrDefault().
To remove or add items, I converted to JArray, which provides Add() and Remove() functionality.
One important thing is to clone elements, which are inserted at a different position. Use DeepClone() to get your new element.
After falling in the trap of quickly hand-editing a large JSON file, I developed a small command-line tool to do the modifications I needed.