using System.Collections.Generic; using System.Linq; using System.Text; using System; namespace Swan.Formatters { internal class HumanizeJson { private readonly StringBuilder _builder = new StringBuilder(); private readonly Int32 _indent; private readonly String _indentStr; private readonly Object _obj; public HumanizeJson(Object obj, Int32 indent) { if(obj == null) { return; } this._indent = indent; this._indentStr = new String(' ', indent * 4); this._obj = obj; this.ParseObject(); } public String GetResult() => this._builder == null ? String.Empty : this._builder.ToString().TrimEnd(); private void ParseObject() { switch(this._obj) { case Dictionary dictionary: this.AppendDictionary(dictionary); break; case List list: this.AppendList(list); break; default: this.AppendString(); break; } } private void AppendDictionary(Dictionary objects) { foreach(KeyValuePair kvp in objects) { if(kvp.Value == null) { continue; } Boolean writeOutput = false; switch(kvp.Value) { case Dictionary valueDictionary: if(valueDictionary.Count > 0) { writeOutput = true; _ = this._builder.Append($"{this._indentStr}{kvp.Key,-16}: object").AppendLine(); } break; case List valueList: if(valueList.Count > 0) { writeOutput = true; _ = this._builder.Append($"{this._indentStr}{kvp.Key,-16}: array[{valueList.Count}]").AppendLine(); } break; default: writeOutput = true; _ = this._builder.Append($"{this._indentStr}{kvp.Key,-16}: "); break; } if(writeOutput) { _ = this._builder.AppendLine(new HumanizeJson(kvp.Value, this._indent + 1).GetResult()); } } } private void AppendList(List objects) { Int32 index = 0; foreach(Object value in objects) { Boolean writeOutput = false; switch(value) { case Dictionary valueDictionary: if(valueDictionary.Count > 0) { writeOutput = true; _ = this._builder.Append($"{this._indentStr}[{index}]: object").AppendLine(); } break; case List valueList: if(valueList.Count > 0) { writeOutput = true; _ = this._builder.Append($"{this._indentStr}[{index}]: array[{valueList.Count}]").AppendLine(); } break; default: writeOutput = true; _ = this._builder.Append($"{this._indentStr}[{index}]: "); break; } index++; if(writeOutput) { _ = this._builder.AppendLine(new HumanizeJson(value, this._indent + 1).GetResult()); } } } private void AppendString() { String stringValue = this._obj.ToString(); if(stringValue.Length + this._indentStr.Length > 96 || stringValue.IndexOf('\r') >= 0 || stringValue.IndexOf('\n') >= 0) { _ = this._builder.AppendLine(); IEnumerable stringLines = stringValue.ToLines().Select(l => l.Trim()); foreach(String line in stringLines) { _ = this._builder.AppendLine($"{this._indentStr}{line}"); } } else { _ = this._builder.Append($"{stringValue}"); } } } }