Skip to content

Instantly share code, notes, and snippets.

@AnsisMalins
Last active March 19, 2019 00:20
Show Gist options
  • Save AnsisMalins/787ba055207f8c4ee9947a35db1da6f8 to your computer and use it in GitHub Desktop.
Save AnsisMalins/787ba055207f8c4ee9947a35db1da6f8 to your computer and use it in GitHub Desktop.
A Very Ghetto JSON Writer
public struct JsonBuilder
{
private StringBuilder sb;
public int Indentation;
public JsonBuilder(StringBuilder sb)
{
Indentation = 0;
this.sb = sb;
}
public void EndArray()
{
Indentation -= 4;
BeforeEndOfItem('[');
sb.Append(']');
}
public void EndObject()
{
Indentation -= 4;
BeforeEndOfItem('{');
sb.Append('}');
}
public void StartArray()
{
BeforeNextItem();
sb.Append('[');
Indentation += 4;
}
public void StartObject()
{
BeforeNextItem();
sb.Append('{');
Indentation += 4;
}
public void WriteName(string name)
{
BeforeNextItem();
sb.Append('"').Append(name).Append("\": ");
}
public void WriteValue(bool value)
{
BeforeNextItem();
sb.Append(value ? "true" : "false");
}
public void WriteValue(double value)
{
BeforeNextItem();
sb.Append(value);
}
public void WriteValue(string value)
{
BeforeNextItem();
if (value != null)
sb.Append('"').Append(value).Append('"');
else
sb.Append("null");
}
private void BeforeEndOfItem(char startChar)
{
char end = sb[sb.Length - 1];
if (end != startChar)
{
sb.Append("\n");
for (int i = 0; i < Indentation; i++)
sb.Append(' ');
}
else if (startChar == '{')
{
sb.Append(' ');
}
}
private void BeforeNextItem()
{
char end = sb.Length > 0 ? sb[sb.Length - 1] : '\0';
if (char.IsLetterOrDigit(end) || end == '"' || end == ']' || end == '}')
sb.Append(",\n");
else if (end == '[' || end == '{')
sb.Append("\n");
if (end != ' ')
for (int i = 0; i < Indentation; i++)
sb.Append(' ');
}
}
@AnsisMalins
Copy link
Author

AnsisMalins commented Mar 18, 2019

For example,

var sb = new StringBuilder();
var json = new JsonBuilder(sb);
json.WriteName("OnPostprocessAllAssets");
json.StartObject();
json.WriteName("importedAssets");
json.StartArray();
foreach (var assetPath in importedAssets)
    json.WriteValue(assetPath);
json.EndArray();
json.WriteName("deletedAssets");
json.StartArray();
foreach (var assetPath in deletedAssets)
    json.WriteValue(assetPath);
json.EndArray();
json.WriteName("movedAssets");
json.StartArray();
foreach (var assetPath in movedAssets)
    json.WriteValue(assetPath);
json.EndArray();
json.WriteName("movedFromAssetPaths");
json.StartArray();
foreach (var assetPath in movedFromAssetPaths)
    json.WriteValue(assetPath);
json.EndArray();
json.EndObject();

will produce

"OnPostprocessAllAssets": {
    "importedAssets": [
        "Assets/Scripts/Editor/DebugProcessor.cs"
    ],
    "deletedAssets": [],
    "movedAssets": [],
    "movedFromAssetPaths": []
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment