source: binary-improvements/7dtd-server-fixes/src/JSON/JSONString.cs@ 327

Last change on this file since 327 was 325, checked in by alloc, 6 years ago

Code style cleanup (mostly whitespace changes, enforcing braces, using cleanup)

File size: 2.4 KB
RevLine 
[160]1using System.Text;
[154]2
[325]3namespace AllocsFixes.JSON {
4 public class JSONString : JSONValue {
5 private readonly string value;
[154]6
[325]7 public JSONString (string value) {
[154]8 this.value = value;
9 }
10
[325]11 public string GetString () {
[187]12 return value;
13 }
14
[325]15 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, int currentLevel = 0) {
[160]16 if (value == null || value.Length == 0) {
[309]17 stringBuilder.Append ("\"\"");
18 return;
[160]19 }
20
21 int len = value.Length;
22
[325]23 stringBuilder.EnsureCapacity (stringBuilder.Length + 2 * len);
[160]24
[309]25 stringBuilder.Append ('"');
26
[160]27 foreach (char c in value) {
28 switch (c) {
29 case '\\':
30 case '"':
[325]31
[306]32// case '/':
[309]33 stringBuilder.Append ('\\');
34 stringBuilder.Append (c);
[160]35 break;
36 case '\b':
[309]37 stringBuilder.Append ("\\b");
[160]38 break;
39 case '\t':
[309]40 stringBuilder.Append ("\\t");
[160]41 break;
42 case '\n':
[309]43 stringBuilder.Append ("\\n");
[160]44 break;
45 case '\f':
[309]46 stringBuilder.Append ("\\f");
[160]47 break;
48 case '\r':
[309]49 stringBuilder.Append ("\\r");
[160]50 break;
51 default:
52 if (c < ' ') {
[309]53 stringBuilder.Append ("\\u");
[325]54 stringBuilder.Append (((int) c).ToString ("X4"));
[160]55 } else {
[309]56 stringBuilder.Append (c);
[160]57 }
[325]58
[160]59 break;
60 }
61 }
62
[309]63 stringBuilder.Append ('"');
[154]64 }
65
[325]66 public static JSONString Parse (string json, ref int offset) {
[187]67 //Log.Out ("ParseString enter (" + offset + ")");
68 StringBuilder sb = new StringBuilder ();
69 offset++;
70 while (offset < json.Length) {
71 switch (json [offset]) {
72 case '\\':
73 offset++;
74 switch (json [offset]) {
75 case '\\':
76 case '"':
77 case '/':
78 sb.Append (json [offset]);
79 break;
80 case 'b':
81 sb.Append ('\b');
82 break;
83 case 't':
84 sb.Append ('\t');
85 break;
86 case 'n':
87 sb.Append ('\n');
88 break;
89 case 'f':
90 sb.Append ('\f');
91 break;
92 case 'r':
93 sb.Append ('\r');
94 break;
95 default:
96 sb.Append (json [offset]);
97 break;
98 }
[325]99
[187]100 offset++;
101 break;
102 case '"':
103 offset++;
[325]104
[187]105 //Log.Out ("JSON:Parsed String: " + sb.ToString ());
106 return new JSONString (sb.ToString ());
107 default:
108 sb.Append (json [offset]);
109 offset++;
110 break;
111 }
112 }
[325]113
[187]114 throw new MalformedJSONException ("End of JSON reached before parsing string finished");
115 }
[154]116 }
[325]117}
Note: See TracBrowser for help on using the repository browser.