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

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

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

File size: 2.4 KB
Line 
1using System.Text;
2
3namespace AllocsFixes.JSON {
4 public class JSONString : JSONValue {
5 private readonly string value;
6
7 public JSONString (string value) {
8 this.value = value;
9 }
10
11 public string GetString () {
12 return value;
13 }
14
15 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, int currentLevel = 0) {
16 if (value == null || value.Length == 0) {
17 stringBuilder.Append ("\"\"");
18 return;
19 }
20
21 int len = value.Length;
22
23 stringBuilder.EnsureCapacity (stringBuilder.Length + 2 * len);
24
25 stringBuilder.Append ('"');
26
27 foreach (char c in value) {
28 switch (c) {
29 case '\\':
30 case '"':
31
32// case '/':
33 stringBuilder.Append ('\\');
34 stringBuilder.Append (c);
35 break;
36 case '\b':
37 stringBuilder.Append ("\\b");
38 break;
39 case '\t':
40 stringBuilder.Append ("\\t");
41 break;
42 case '\n':
43 stringBuilder.Append ("\\n");
44 break;
45 case '\f':
46 stringBuilder.Append ("\\f");
47 break;
48 case '\r':
49 stringBuilder.Append ("\\r");
50 break;
51 default:
52 if (c < ' ') {
53 stringBuilder.Append ("\\u");
54 stringBuilder.Append (((int) c).ToString ("X4"));
55 } else {
56 stringBuilder.Append (c);
57 }
58
59 break;
60 }
61 }
62
63 stringBuilder.Append ('"');
64 }
65
66 public static JSONString Parse (string json, ref int offset) {
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 }
99
100 offset++;
101 break;
102 case '"':
103 offset++;
104
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 }
113
114 throw new MalformedJSONException ("End of JSON reached before parsing string finished");
115 }
116 }
117}
Note: See TracBrowser for help on using the repository browser.