2 using System.Collections;
3 using System.Collections.Generic;
4 using System.Globalization;
10 public class JsonPrimitive : JsonValue
14 public JsonPrimitive (bool value)
19 public JsonPrimitive (byte value)
24 public JsonPrimitive (char value)
29 public JsonPrimitive (decimal value)
34 public JsonPrimitive (double value)
39 public JsonPrimitive (float value)
44 public JsonPrimitive (int value)
49 public JsonPrimitive (long value)
54 public JsonPrimitive (sbyte value)
59 public JsonPrimitive (short value)
64 public JsonPrimitive (string value)
69 public JsonPrimitive (DateTime value)
74 public JsonPrimitive (uint value)
79 public JsonPrimitive (ulong value)
84 public JsonPrimitive (ushort value)
89 public JsonPrimitive (DateTimeOffset value)
94 public JsonPrimitive (Guid value)
99 public JsonPrimitive (TimeSpan value)
104 public JsonPrimitive (Uri value)
109 internal object Value {
110 get { return value; }
113 public override JsonType JsonType {
115 // FIXME: what should we do for null? Handle it as null so far.
117 return JsonType.String;
119 switch (Type.GetTypeCode (value.GetType ())) {
120 case TypeCode.Boolean:
121 return JsonType.Boolean;
123 case TypeCode.String:
124 case TypeCode.DateTime:
125 case TypeCode.Object: // DateTimeOffset || Guid || TimeSpan || Uri
126 return JsonType.String;
128 return JsonType.Number;
133 static readonly byte [] true_bytes = Encoding.UTF8.GetBytes ("true");
134 static readonly byte [] false_bytes = Encoding.UTF8.GetBytes ("false");
136 public override void Save (Stream stream)
139 case JsonType.Boolean:
141 stream.Write (true_bytes, 0, 4);
143 stream.Write (false_bytes, 0, 5);
145 case JsonType.String:
146 stream.WriteByte ((byte) '\"');
147 byte [] bytes = Encoding.UTF8.GetBytes (EscapeString (value.ToString ()));
148 stream.Write (bytes, 0, bytes.Length);
149 stream.WriteByte ((byte) '\"');
152 bytes = Encoding.UTF8.GetBytes (GetFormattedString ());
153 stream.Write (bytes, 0, bytes.Length);
158 internal string GetFormattedString ()
161 case JsonType.String:
162 if (value is string || value == null)
163 return (string) value;
164 throw new NotImplementedException ("GetFormattedString from value type " + value.GetType ());
165 case JsonType.Number:
166 return ((IFormattable) value).ToString ("G", NumberFormatInfo.InvariantInfo);
168 throw new InvalidOperationException ();