source: binary-improvements2/7dtd-server-fixes/src/JSON/JSONString.cs@ 381

Last change on this file since 381 was 351, checked in by alloc, 6 years ago

Fixed game version compatibility of GamePrefs
Code style cleanup (mostly argument names)

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 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.