123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- #if !SILVERLIGHT
- using System.Data;
- #endif
- using System.Globalization;
- using System.IO;
- using System.Text;
- using System.Collections.Specialized;
- namespace fastJSON
- {
- internal sealed class JSONSerializer
- {
- private StringBuilder _output = new StringBuilder();
- //private StringBuilder _before = new StringBuilder();
- private int _before;
- private int _MAX_DEPTH = 20;
- int _current_depth = 0;
- private Dictionary<string, int> _globalTypes = new Dictionary<string, int>();
- private Dictionary<object, int> _cirobj = new Dictionary<object, int>();
- private JSONParameters _params;
- private bool _useEscapedUnicode = false;
- internal JSONSerializer(JSONParameters param)
- {
- _params = param;
- _useEscapedUnicode = _params.UseEscapedUnicode;
- _MAX_DEPTH = _params.SerializerMaxDepth;
- }
- internal string ConvertToJSON(object obj)
- {
- WriteValue(obj);
- if (_params.UsingGlobalTypes && _globalTypes != null && _globalTypes.Count > 0)
- {
- var sb = new StringBuilder();
- sb.Append("\"$types\":{");
- var pendingSeparator = false;
- foreach (var kv in _globalTypes)
- {
- if (pendingSeparator) sb.Append(',');
- pendingSeparator = true;
- sb.Append('\"');
- sb.Append(kv.Key);
- sb.Append("\":\"");
- sb.Append(kv.Value);
- sb.Append('\"');
- }
- sb.Append("},");
- _output.Insert(_before, sb.ToString());
- }
- return _output.ToString();
- }
- private void WriteValue(object obj)
- {
- if (obj == null || obj is DBNull)
- _output.Append("null");
- else if (obj is string || obj is char)
- WriteString(obj.ToString());
- else if (obj is Guid)
- WriteGuid((Guid)obj);
- else if (obj is bool)
- _output.Append(((bool)obj) ? "true" : "false"); // conform to standard
- else if (
- obj is int || obj is long ||
- obj is decimal ||
- obj is byte || obj is short ||
- obj is sbyte || obj is ushort ||
- obj is uint || obj is ulong
- )
- _output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo));
- else if (obj is double || obj is Double)
- {
- double d = (double)obj;
- if (double.IsNaN(d))
- _output.Append("\"NaN\"");
- else
- _output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo));
- }
- else if (obj is float || obj is Single)
- {
- float d = (float)obj;
- if (float.IsNaN(d))
- _output.Append("\"NaN\"");
- else
- _output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo));
- }
- else if (obj is DateTime)
- WriteDateTime((DateTime)obj);
- else if (obj is DateTimeOffset)
- WriteDateTimeOffset((DateTimeOffset)obj);
- else if (obj is TimeSpan)
- _output.Append(((TimeSpan)obj).Ticks);
- #if net4
- else if (_params.KVStyleStringDictionary == false &&
- obj is IEnumerable<KeyValuePair<string, object>>)
- WriteStringDictionary((IEnumerable<KeyValuePair<string, object>>)obj);
- #endif
- else if (_params.KVStyleStringDictionary == false && obj is IDictionary &&
- obj.GetType().IsGenericType && obj.GetType().GetGenericArguments()[0] == typeof(string))
- WriteStringDictionary((IDictionary)obj);
- else if (obj is IDictionary)
- WriteDictionary((IDictionary)obj);
- #if !SILVERLIGHT
- else if (obj is DataSet)
- WriteDataset((DataSet)obj);
- else if (obj is DataTable)
- this.WriteDataTable((DataTable)obj);
- #endif
- else if (obj is byte[])
- WriteBytes((byte[])obj);
- else if (obj is StringDictionary)
- WriteSD((StringDictionary)obj);
- else if (obj is NameValueCollection)
- WriteNV((NameValueCollection)obj);
- else if (obj is IEnumerable)
- WriteArray((IEnumerable)obj);
- else if (obj is Enum)
- WriteEnum((Enum)obj);
- else if (Reflection.Instance.IsTypeRegistered(obj.GetType()))
- WriteCustom(obj);
- else
- WriteObject(obj);
- }
- private void WriteDateTimeOffset(DateTimeOffset d)
- {
- write_date_value(d.DateTime);
- _output.Append(" ");
- if (d.Offset.Hours > 0)
- _output.Append("+");
- else
- _output.Append("-");
- _output.Append(d.Offset.Hours.ToString("00", NumberFormatInfo.InvariantInfo));
- _output.Append(":");
- _output.Append(d.Offset.Minutes);
- _output.Append('\"');
- }
- private void WriteNV(NameValueCollection nameValueCollection)
- {
- _output.Append('{');
- bool pendingSeparator = false;
- foreach (string key in nameValueCollection)
- {
- if (_params.SerializeNullValues == false && (nameValueCollection[key] == null))
- {
- }
- else
- {
- if (pendingSeparator) _output.Append(',');
- if (_params.SerializeToLowerCaseNames)
- WritePair(key.ToLower(), nameValueCollection[key]);
- else
- WritePair(key, nameValueCollection[key]);
- pendingSeparator = true;
- }
- }
- _output.Append('}');
- }
- private void WriteSD(StringDictionary stringDictionary)
- {
- _output.Append('{');
- bool pendingSeparator = false;
- foreach (DictionaryEntry entry in stringDictionary)
- {
- if (_params.SerializeNullValues == false && (entry.Value == null))
- {
- }
- else
- {
- if (pendingSeparator) _output.Append(',');
- string k = (string)entry.Key;
- if (_params.SerializeToLowerCaseNames)
- WritePair(k.ToLower(), entry.Value);
- else
- WritePair(k, entry.Value);
- pendingSeparator = true;
- }
- }
- _output.Append('}');
- }
- private void WriteCustom(object obj)
- {
- Serialize s;
- Reflection.Instance._customSerializer.TryGetValue(obj.GetType(), out s);
- WriteStringFast(s(obj));
- }
- private void WriteEnum(Enum e)
- {
- // FEATURE : optimize enum write
- if (_params.UseValuesOfEnums)
- WriteValue(Convert.ToInt32(e));
- else
- WriteStringFast(e.ToString());
- }
- private void WriteGuid(Guid g)
- {
- if (_params.UseFastGuid == false)
- WriteStringFast(g.ToString());
- else
- WriteBytes(g.ToByteArray());
- }
- private void WriteBytes(byte[] bytes)
- {
- #if !SILVERLIGHT
- WriteStringFast(Convert.ToBase64String(bytes, 0, bytes.Length, Base64FormattingOptions.None));
- #else
- WriteStringFast(Convert.ToBase64String(bytes, 0, bytes.Length));
- #endif
- }
- private void WriteDateTime(DateTime dateTime)
- {
- // datetime format standard : yyyy-MM-dd HH:mm:ss
- DateTime dt = dateTime;
- if (_params.UseUTCDateTime)
- dt = dateTime.ToUniversalTime();
- write_date_value(dt);
- if (_params.UseUTCDateTime)
- _output.Append('Z');
- _output.Append('\"');
- }
- private void write_date_value(DateTime dt)
- {
- _output.Append('\"');
- _output.Append(dt.Year.ToString("0000", NumberFormatInfo.InvariantInfo));
- _output.Append('-');
- _output.Append(dt.Month.ToString("00", NumberFormatInfo.InvariantInfo));
- _output.Append('-');
- _output.Append(dt.Day.ToString("00", NumberFormatInfo.InvariantInfo));
- _output.Append('T'); // strict ISO date compliance
- _output.Append(dt.Hour.ToString("00", NumberFormatInfo.InvariantInfo));
- _output.Append(':');
- _output.Append(dt.Minute.ToString("00", NumberFormatInfo.InvariantInfo));
- _output.Append(':');
- _output.Append(dt.Second.ToString("00", NumberFormatInfo.InvariantInfo));
- if (_params.DateTimeMilliseconds)
- {
- _output.Append('.');
- _output.Append(dt.Millisecond.ToString("000", NumberFormatInfo.InvariantInfo));
- }
- }
- #if !SILVERLIGHT
- private DatasetSchema GetSchema(DataTable ds)
- {
- if (ds == null) return null;
- DatasetSchema m = new DatasetSchema();
- m.Info = new List<string>();
- m.Name = ds.TableName;
- foreach (DataColumn c in ds.Columns)
- {
- m.Info.Add(ds.TableName);
- m.Info.Add(c.ColumnName);
- m.Info.Add(c.DataType.ToString());
- }
- // FEATURE : serialize relations and constraints here
- return m;
- }
- private DatasetSchema GetSchema(DataSet ds)
- {
- if (ds == null) return null;
- DatasetSchema m = new DatasetSchema();
- m.Info = new List<string>();
- m.Name = ds.DataSetName;
- foreach (DataTable t in ds.Tables)
- {
- foreach (DataColumn c in t.Columns)
- {
- m.Info.Add(t.TableName);
- m.Info.Add(c.ColumnName);
- m.Info.Add(c.DataType.ToString());
- }
- }
- // FEATURE : serialize relations and constraints here
- return m;
- }
- private string GetXmlSchema(DataTable dt)
- {
- using (var writer = new StringWriter())
- {
- dt.WriteXmlSchema(writer);
- return dt.ToString();
- }
- }
- private void WriteDataset(DataSet ds)
- {
- _output.Append('{');
- if (_params.UseExtensions)
- {
- WritePair("$schema", _params.UseOptimizedDatasetSchema ? (object)GetSchema(ds) : ds.GetXmlSchema());
- _output.Append(',');
- }
- bool tablesep = false;
- foreach (DataTable table in ds.Tables)
- {
- if (tablesep) _output.Append(',');
- tablesep = true;
- WriteDataTableData(table);
- }
- // end dataset
- _output.Append('}');
- }
- private void WriteDataTableData(DataTable table)
- {
- _output.Append('\"');
- _output.Append(table.TableName);
- _output.Append("\":[");
- DataColumnCollection cols = table.Columns;
- bool rowseparator = false;
- foreach (DataRow row in table.Rows)
- {
- if (rowseparator) _output.Append(',');
- rowseparator = true;
- _output.Append('[');
- bool pendingSeperator = false;
- foreach (DataColumn column in cols)
- {
- if (pendingSeperator) _output.Append(',');
- WriteValue(row[column]);
- pendingSeperator = true;
- }
- _output.Append(']');
- }
- _output.Append(']');
- }
- void WriteDataTable(DataTable dt)
- {
- this._output.Append('{');
- if (_params.UseExtensions)
- {
- this.WritePair("$schema", _params.UseOptimizedDatasetSchema ? (object)this.GetSchema(dt) : this.GetXmlSchema(dt));
- this._output.Append(',');
- }
- WriteDataTableData(dt);
- // end datatable
- this._output.Append('}');
- }
- #endif
- bool _TypesWritten = false;
- private void WriteObject(object obj)
- {
- int i = 0;
- if (_cirobj.TryGetValue(obj, out i) == false)
- _cirobj.Add(obj, _cirobj.Count + 1);
- else
- {
- if (_current_depth > 0 && _params.InlineCircularReferences == false)
- {
- //_circular = true;
- _output.Append("{\"$i\":");
- _output.Append(i.ToString());
- _output.Append("}");
- return;
- }
- }
- if (_params.UsingGlobalTypes == false)
- _output.Append('{');
- else
- {
- if (_TypesWritten == false)
- {
- _output.Append('{');
- _before = _output.Length;
- //_output = new StringBuilder();
- }
- else
- _output.Append('{');
- }
- _TypesWritten = true;
- _current_depth++;
- if (_current_depth > _MAX_DEPTH)
- throw new Exception("Serializer encountered maximum depth of " + _MAX_DEPTH);
- Dictionary<string, string> map = new Dictionary<string, string>();
- Type t = obj.GetType();
- bool append = false;
- if (_params.UseExtensions)
- {
- if (_params.UsingGlobalTypes == false)
- WritePairFast("$type", Reflection.Instance.GetTypeAssemblyName(t));
- else
- {
- int dt = 0;
- string ct = Reflection.Instance.GetTypeAssemblyName(t);
- if (_globalTypes.TryGetValue(ct, out dt) == false)
- {
- dt = _globalTypes.Count + 1;
- _globalTypes.Add(ct, dt);
- }
- WritePairFast("$type", dt.ToString());
- }
- append = true;
- }
- Getters[] g = Reflection.Instance.GetGetters(t, _params.ShowReadOnlyProperties, _params.IgnoreAttributes);
- int c = g.Length;
- for (int ii = 0; ii < c; ii++)
- {
- var p = g[ii];
- object o = p.Getter(obj);
- if (_params.SerializeNullValues == false && (o == null || o is DBNull))
- {
- //append = false;
- }
- else
- {
- if (append)
- _output.Append(',');
- if (_params.SerializeToLowerCaseNames)
- WritePair(p.lcName, o);
- else
- WritePair(p.Name, o);
- if (o != null && _params.UseExtensions)
- {
- Type tt = o.GetType();
- if (tt == typeof(System.Object))
- map.Add(p.Name, tt.ToString());
- }
- append = true;
- }
- }
- if (map.Count > 0 && _params.UseExtensions)
- {
- _output.Append(",\"$map\":");
- WriteStringDictionary(map);
- }
- _output.Append('}');
- _current_depth--;
- }
- private void WritePairFast(string name, string value)
- {
- WriteStringFast(name);
- _output.Append(':');
- WriteStringFast(value);
- }
- private void WritePair(string name, object value)
- {
- WriteString(name);
- _output.Append(':');
- WriteValue(value);
- }
- private void WriteArray(IEnumerable array)
- {
- _output.Append('[');
- bool pendingSeperator = false;
- foreach (object obj in array)
- {
- if (pendingSeperator) _output.Append(',');
- WriteValue(obj);
- pendingSeperator = true;
- }
- _output.Append(']');
- }
- private void WriteStringDictionary(IDictionary dic)
- {
- _output.Append('{');
- bool pendingSeparator = false;
- foreach (DictionaryEntry entry in dic)
- {
- if (_params.SerializeNullValues == false && (entry.Value == null))
- {
- }
- else
- {
- if (pendingSeparator) _output.Append(',');
- string k = (string)entry.Key;
- if (_params.SerializeToLowerCaseNames)
- WritePair(k.ToLower(), entry.Value);
- else
- WritePair(k, entry.Value);
- pendingSeparator = true;
- }
- }
- _output.Append('}');
- }
- private void WriteStringDictionary(IEnumerable<KeyValuePair<string, object>> dic)
- {
- _output.Append('{');
- bool pendingSeparator = false;
- foreach (KeyValuePair<string, object> entry in dic)
- {
- if (_params.SerializeNullValues == false && (entry.Value == null))
- {
- }
- else
- {
- if (pendingSeparator) _output.Append(',');
- string k = entry.Key;
- if (_params.SerializeToLowerCaseNames)
- WritePair(k.ToLower(), entry.Value);
- else
- WritePair(k, entry.Value);
- pendingSeparator = true;
- }
- }
- _output.Append('}');
- }
- private void WriteDictionary(IDictionary dic)
- {
- _output.Append('[');
- bool pendingSeparator = false;
- foreach (DictionaryEntry entry in dic)
- {
- if (pendingSeparator) _output.Append(',');
- _output.Append('{');
- WritePair("k", entry.Key);
- _output.Append(",");
- WritePair("v", entry.Value);
- _output.Append('}');
- pendingSeparator = true;
- }
- _output.Append(']');
- }
- private void WriteStringFast(string s)
- {
- _output.Append('\"');
- _output.Append(s);
- _output.Append('\"');
- }
- private void WriteString(string s)
- {
- _output.Append('\"');
- int runIndex = -1;
- int l = s.Length;
- for (var index = 0; index < l; ++index)
- {
- var c = s[index];
- if (_useEscapedUnicode)
- {
- if (c >= ' ' && c < 128 && c != '\"' && c != '\\')
- {
- if (runIndex == -1)
- runIndex = index;
- continue;
- }
- }
- else
- {
- if (c != '\t' && c != '\n' && c != '\r' && c != '\"' && c != '\\')// && c != ':' && c!=',')
- {
- if (runIndex == -1)
- runIndex = index;
- continue;
- }
- }
- if (runIndex != -1)
- {
- _output.Append(s, runIndex, index - runIndex);
- runIndex = -1;
- }
- switch (c)
- {
- case '\t': _output.Append("\\t"); break;
- case '\r': _output.Append("\\r"); break;
- case '\n': _output.Append("\\n"); break;
- case '"':
- case '\\': _output.Append('\\'); _output.Append(c); break;
- default:
- if (_useEscapedUnicode)
- {
- _output.Append("\\u");
- _output.Append(((int)c).ToString("X4", NumberFormatInfo.InvariantInfo));
- }
- else
- _output.Append(c);
- break;
- }
- }
- if (runIndex != -1)
- _output.Append(s, runIndex, s.Length - runIndex);
- _output.Append('\"');
- }
- }
- }
|