source: binary-improvements2/7dtd-server-fixes/src/JSON/JSONArray.cs@ 400

Last change on this file since 400 was 391, checked in by alloc, 2 years ago

Major refactoring/cleanup

File size: 1.9 KB
Line 
1using System.Collections.Generic;
2using System.Text;
3
4namespace AllocsFixes.JSON {
5 public class JsonArray : JsonNode {
6 private readonly List<JsonNode> nodes = new List<JsonNode> ();
7
8 public JsonNode this [int _index] {
9 get => nodes [_index];
10 set => nodes [_index] = value;
11 }
12
13 public int Count => nodes.Count;
14
15 public void Add (JsonNode _node) {
16 nodes.Add (_node);
17 }
18
19 public override void ToString (StringBuilder _stringBuilder, bool _prettyPrint = false, int _currentLevel = 0) {
20 _stringBuilder.Append ("[");
21 if (_prettyPrint) {
22 _stringBuilder.Append ('\n');
23 }
24
25 foreach (JsonNode n in nodes) {
26 if (_prettyPrint) {
27 _stringBuilder.Append (new string ('\t', _currentLevel + 1));
28 }
29
30 n.ToString (_stringBuilder, _prettyPrint, _currentLevel + 1);
31 _stringBuilder.Append (",");
32 if (_prettyPrint) {
33 _stringBuilder.Append ('\n');
34 }
35 }
36
37 if (nodes.Count > 0) {
38 _stringBuilder.Remove (_stringBuilder.Length - (_prettyPrint ? 2 : 1), 1);
39 }
40
41 if (_prettyPrint) {
42 _stringBuilder.Append (new string ('\t', _currentLevel));
43 }
44
45 _stringBuilder.Append ("]");
46 }
47
48 public static JsonArray Parse (string _json, ref int _offset) {
49 //Log.Out ("ParseArray enter (" + offset + ")");
50 JsonArray arr = new JsonArray ();
51
52 bool nextElemAllowed = true;
53 _offset++;
54 while (true) {
55 Parser.SkipWhitespace (_json, ref _offset);
56
57 switch (_json [_offset]) {
58 case ',':
59 if (!nextElemAllowed) {
60 nextElemAllowed = true;
61 _offset++;
62 } else {
63 throw new MalformedJsonException (
64 "Could not parse array, found a comma without a value first");
65 }
66
67 break;
68 case ']':
69 _offset++;
70
71 //Log.Out ("JSON:Parsed Array: " + arr.ToString ());
72 return arr;
73 default:
74 arr.Add (Parser.ParseInternal (_json, ref _offset));
75 nextElemAllowed = false;
76 break;
77 }
78 }
79 }
80 }
81}
Note: See TracBrowser for help on using the repository browser.