Last active
March 19, 2019 00:20
-
-
Save AnsisMalins/787ba055207f8c4ee9947a35db1da6f8 to your computer and use it in GitHub Desktop.
A Very Ghetto JSON Writer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(' '); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For example,
will produce