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

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

Fixes 14_16_21

File size: 2.4 KB
RevLine 
[154]1using System;
[160]2using System.Text;
[154]3
4namespace AllocsFixes.JSON
5{
[279]6 public class JSONString : JSONValue
[154]7 {
8 private string value;
9
10 public JSONString (string value)
11 {
12 this.value = value;
13 }
14
[187]15 public string GetString ()
[154]16 {
[187]17 return value;
18 }
19
[309]20 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, int currentLevel = 0)
[187]21 {
[160]22 if (value == null || value.Length == 0) {
[309]23 stringBuilder.Append ("\"\"");
24 return;
[160]25 }
26
27 int len = value.Length;
28
[309]29 stringBuilder.EnsureCapacity (stringBuilder.Length + 2*len);
[160]30 String t;
31
[309]32 stringBuilder.Append ('"');
33
[160]34 foreach (char c in value) {
35 switch (c) {
36 case '\\':
37 case '"':
[306]38// case '/':
[309]39 stringBuilder.Append ('\\');
40 stringBuilder.Append (c);
[160]41 break;
42 case '\b':
[309]43 stringBuilder.Append ("\\b");
[160]44 break;
45 case '\t':
[309]46 stringBuilder.Append ("\\t");
[160]47 break;
48 case '\n':
[309]49 stringBuilder.Append ("\\n");
[160]50 break;
51 case '\f':
[309]52 stringBuilder.Append ("\\f");
[160]53 break;
54 case '\r':
[309]55 stringBuilder.Append ("\\r");
[160]56 break;
57 default:
58 if (c < ' ') {
[309]59 stringBuilder.Append ("\\u");
60 stringBuilder.Append (((int)c).ToString ("X4"));
[160]61 } else {
[309]62 stringBuilder.Append (c);
[160]63 }
64 break;
65 }
66 }
67
[309]68 stringBuilder.Append ('"');
[154]69 }
70
[187]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
[154]120 }
121}
122
Note: See TracBrowser for help on using the repository browser.