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

Last change on this file since 217 was 187, checked in by alloc, 10 years ago

fixes

File size: 2.6 KB
RevLine 
[154]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
[187]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
[154]29 public void Add (string name, JSONNode node)
30 {
31 nodes.Add (name, node);
32 }
33
[187]34 public override string ToString (bool prettyPrint = false, int currentLevel = 0)
[154]35 {
36 StringBuilder sb = new StringBuilder ("{");
[187]37 if (prettyPrint)
38 sb.Append ('\n');
[154]39 foreach (KeyValuePair<string, JSONNode> kvp in nodes) {
[187]40 if (prettyPrint)
41 sb.Append (new String ('\t', currentLevel + 1));
[154]42 sb.Append (String.Format ("\"{0}\":", kvp.Key));
[187]43 if (prettyPrint)
44 sb.Append (" ");
45 sb.Append (kvp.Value.ToString (prettyPrint, currentLevel + 1));
[154]46 sb.Append (",");
[187]47 if (prettyPrint)
48 sb.Append ('\n');
[154]49 }
50 if (sb.Length > 1)
[187]51 sb.Remove (sb.Length - (prettyPrint ? 2 : 1), 1);
52 if (prettyPrint)
53 sb.Append (new String ('\t', currentLevel));
[154]54 sb.Append ("}");
55 return sb.ToString ();
56 }
57
[187]58 public static JSONObject Parse (string json, ref int offset)
59 {
60 //Log.Out ("ParseObject enter (" + offset + ")");
61 JSONObject obj = new JSONObject ();
62
63 bool nextElemAllowed = true;
64 offset++;
65 while (true) {
66 Parser.SkipWhitespace (json, ref offset);
67 switch (json [offset]) {
68 case '"':
69 if (nextElemAllowed) {
70 JSONString key = JSONString.Parse (json, ref offset);
71 Parser.SkipWhitespace (json, ref offset);
72 if (json [offset] != ':') {
73 throw new MalformedJSONException ("Could not parse object, missing colon (\":\") after key");
74 }
75 offset++;
76 JSONNode val = Parser.ParseInternal (json, ref offset);
77 obj.Add (key.GetString (), val);
78 nextElemAllowed = false;
79 } else {
80 throw new MalformedJSONException ("Could not parse object, found new key without a separating comma");
81 }
82 break;
83 case ',':
84 if (!nextElemAllowed) {
85 nextElemAllowed = true;
86 offset++;
87 } else
88 throw new MalformedJSONException ("Could not parse object, found a comma without a key/value pair first");
89 break;
90 case '}':
91 offset++;
92 //Log.Out ("JSON:Parsed Object: " + obj.ToString ());
93 return obj;
94 }
95 }
96 }
97
[154]98 }
99}
100
Note: See TracBrowser for help on using the repository browser.