- Timestamp:
- Sep 10, 2014, 8:09:28 PM (10 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
binary-improvements/7dtd-server-fixes/src/JSON/JSONObject.cs
r154 r187 9 9 private Dictionary<string, JSONNode> nodes = new Dictionary<string, JSONNode> (); 10 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 11 29 public void Add (string name, JSONNode node) 12 30 { … … 14 32 } 15 33 16 public override string ToString ( )34 public override string ToString (bool prettyPrint = false, int currentLevel = 0) 17 35 { 18 36 StringBuilder sb = new StringBuilder ("{"); 37 if (prettyPrint) 38 sb.Append ('\n'); 19 39 foreach (KeyValuePair<string, JSONNode> kvp in nodes) { 40 if (prettyPrint) 41 sb.Append (new String ('\t', currentLevel + 1)); 20 42 sb.Append (String.Format ("\"{0}\":", kvp.Key)); 21 sb.Append (kvp.Value.ToString ()); 43 if (prettyPrint) 44 sb.Append (" "); 45 sb.Append (kvp.Value.ToString (prettyPrint, currentLevel + 1)); 22 46 sb.Append (","); 47 if (prettyPrint) 48 sb.Append ('\n'); 23 49 } 24 50 if (sb.Length > 1) 25 sb.Remove (sb.Length - 1, 1); 51 sb.Remove (sb.Length - (prettyPrint ? 2 : 1), 1); 52 if (prettyPrint) 53 sb.Append (new String ('\t', currentLevel)); 26 54 sb.Append ("}"); 27 55 return sb.ToString (); 56 } 57 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 } 28 96 } 29 97
Note:
See TracChangeset
for help on using the changeset viewer.