JSON auto formatting

This commit is contained in:
Terry Hearst 2023-10-24 23:07:11 -04:00
parent e424692f58
commit 56f56ef938
2 changed files with 40 additions and 6 deletions

View file

@ -115,13 +115,13 @@ namespace CustomCosmeticLoader
{
JSONNode node = new JSONClass
{
{ PROPERTY_ENABLED, enabled ? "true" : "false" },
{ PROPERTY_ENABLED, new JSONData(enabled) },
{ PROPERTY_CURRENT_SKIN, currentSkin },
{ PROPERTY_SKIN_NAME_TO_HIJACK, skinNameToHijack },
{ PROPERTY_IN_MAIN_MENU, inMainMenu ? "true" : "false" },
{ PROPERTY_IN_COSMETIC_MENU, inCosmeticMenu ? "true" : "false" },
{ PROPERTY_IN_ALL_REPLAYS, inAllReplays ? "true" : "false" },
{ PROPERTY_OVERRIDE_REPLAY_COSMETICS, overrideReplayCosmetics ? "true" : "false" },
{ PROPERTY_IN_MAIN_MENU, new JSONData(inMainMenu) },
{ PROPERTY_IN_COSMETIC_MENU, new JSONData(inCosmeticMenu) },
{ PROPERTY_IN_ALL_REPLAYS, new JSONData(inAllReplays) },
{ PROPERTY_OVERRIDE_REPLAY_COSMETICS, new JSONData(overrideReplayCosmetics) },
};
JSONNode otherPlayersData = new JSONClass();
@ -130,7 +130,7 @@ namespace CustomCosmeticLoader
node.Add(PROPERTY_OTHER_PLAYERS, otherPlayersData);
File.WriteAllText(GetConfigPath(), node.ToString());
File.WriteAllText(GetConfigPath(), JsonHelper.FormatJson(node.ToString(), "\t"));
}
public static void ensureSkinSelected()

34
JsonHelper.cs Normal file
View file

@ -0,0 +1,34 @@
using System;
using System.Linq;
namespace CustomCosmeticLoader
{
public class JsonHelper
{
/*
* Code taken from: https://stackoverflow.com/a/57100143
*/
public static string FormatJson(string json, string indent = " ")
{
var indentation = 0;
var quoteCount = 0;
var escapeCount = 0;
var result =
from ch in json ?? string.Empty
let escaped = (ch == '\\' ? escapeCount++ : escapeCount > 0 ? escapeCount-- : escapeCount) > 0
let quotes = ch == '"' && !escaped ? quoteCount++ : quoteCount
let unquoted = quotes % 2 == 0
let colon = ch == ':' && unquoted ? ": " : null
let nospace = char.IsWhiteSpace(ch) && unquoted ? string.Empty : null
let lineBreak = ch == ',' && unquoted ? ch + Environment.NewLine + string.Concat(Enumerable.Repeat(indent, indentation)) : null
let openChar = (ch == '{' || ch == '[') && unquoted ? ch + Environment.NewLine + string.Concat(Enumerable.Repeat(indent, ++indentation)) : ch.ToString()
let closeChar = (ch == '}' || ch == ']') && unquoted ? Environment.NewLine + string.Concat(Enumerable.Repeat(indent, --indentation)) + ch : ch.ToString()
select colon ?? nospace ?? lineBreak ?? (
openChar.Length > 1 ? openChar : closeChar
);
return string.Concat(result);
}
}
}