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

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

Major refactoring/cleanup

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