source: binary-improvements/7dtd-server-fixes/src/JSON/JSONObject.cs@ 319

Last change on this file since 319 was 315, checked in by alloc, 7 years ago

Fixes

File size: 2.7 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Text;
4
5namespace AllocsFixes.JSON
6{
7 public class JSONObject : JSONNode
8 {
9 private Dictionary<string, JSONNode> nodes = new Dictionary<string, JSONNode> ();
10
11 public JSONNode this [string name] {
12 get { return nodes [name]; }
13 set { nodes [name] = value; }
14 }
15
16 public int Count {
17 get { return nodes.Count; }
18 }
19
20 public List<string> Keys {
21 get { return new List<string> (nodes.Keys); }
22 }
23
24 public bool ContainsKey (string name)
25 {
26 return nodes.ContainsKey (name);
27 }
28
29 public void Add (string name, JSONNode node)
30 {
31 nodes.Add (name, node);
32 }
33
34 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, int currentLevel = 0)
35 {
36 stringBuilder.Append ("{");
37 if (prettyPrint)
38 stringBuilder.Append ('\n');
39 foreach (KeyValuePair<string, JSONNode> kvp in nodes) {
40 if (prettyPrint)
41 stringBuilder.Append (new String ('\t', currentLevel + 1));
42 stringBuilder.Append (String.Format ("\"{0}\":", kvp.Key));
43 if (prettyPrint)
44 stringBuilder.Append (" ");
45 kvp.Value.ToString (stringBuilder, prettyPrint, currentLevel + 1);
46 stringBuilder.Append (",");
47 if (prettyPrint)
48 stringBuilder.Append ('\n');
49 }
50 if (nodes.Count > 0)
51 stringBuilder.Remove (stringBuilder.Length - (prettyPrint ? 2 : 1), 1);
52 if (prettyPrint)
53 stringBuilder.Append (new String ('\t', currentLevel));
54 stringBuilder.Append ("}");
55 }
56
57 public static JSONObject Parse (string json, ref int offset)
58 {
59 //Log.Out ("ParseObject enter (" + offset + ")");
60 JSONObject obj = new JSONObject ();
61
62 bool nextElemAllowed = true;
63 offset++;
64 while (true) {
65 Parser.SkipWhitespace (json, ref offset);
66 switch (json [offset]) {
67 case '"':
68 if (nextElemAllowed) {
69 JSONString key = JSONString.Parse (json, ref offset);
70 Parser.SkipWhitespace (json, ref offset);
71 if (json [offset] != ':') {
72 throw new MalformedJSONException ("Could not parse object, missing colon (\":\") after key");
73 }
74 offset++;
75 JSONNode val = Parser.ParseInternal (json, ref offset);
76 obj.Add (key.GetString (), val);
77 nextElemAllowed = false;
78 } else {
79 throw new MalformedJSONException ("Could not parse object, found new key without a separating comma");
80 }
81 break;
82 case ',':
83 if (!nextElemAllowed) {
84 nextElemAllowed = true;
85 offset++;
86 } else
87 throw new MalformedJSONException ("Could not parse object, found a comma without a key/value pair first");
88 break;
89 case '}':
90 offset++;
91 //Log.Out ("JSON:Parsed Object: " + obj.ToString ());
92 return obj;
93 }
94 }
95 }
96
97 }
98}
99
Note: See TracBrowser for help on using the repository browser.