RaspberryIO/Unosquare.Swan.Lite/Formatters/HumanizeJson.cs
2019-12-04 17:10:06 +01:00

134 lines
4.0 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Unosquare.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<String, Object> dictionary:
this.AppendDictionary(dictionary);
break;
case List<Object> list:
this.AppendList(list);
break;
default:
this.AppendString();
break;
}
}
private void AppendDictionary(Dictionary<String, Object> objects) {
foreach(KeyValuePair<String, Object> kvp in objects) {
if(kvp.Value == null) {
continue;
}
Boolean writeOutput = false;
switch(kvp.Value) {
case Dictionary<String, Object> valueDictionary:
if(valueDictionary.Count > 0) {
writeOutput = true;
_ = this._builder
.Append($"{this._indentStr}{kvp.Key,-16}: object")
.AppendLine();
}
break;
case List<Object> 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<Object> objects) {
Int32 index = 0;
foreach(Object value in objects) {
Boolean writeOutput = false;
switch(value) {
case Dictionary<String, Object> valueDictionary:
if(valueDictionary.Count > 0) {
writeOutput = true;
_ = this._builder
.Append($"{this._indentStr}[{index}]: object")
.AppendLine();
}
break;
case List<Object> 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<String> stringLines = stringValue.ToLines().Select(l => l.Trim());
foreach(String line in stringLines) {
_ = this._builder.AppendLine($"{this._indentStr}{line}");
}
} else {
_ = this._builder.Append($"{stringValue}");
}
}
}
}