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

Last change on this file since 311 was 309, checked in by alloc, 7 years ago

Fixes 14_16_21

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