1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221 |
- #if NETFX_CORE
- #define SIMPLE_JSON_TYPEINFO
- #endif
- using System;
- using System.Collections;
- using System.Collections.Generic;
- #if !SIMPLE_JSON_NO_LINQ_EXPRESSION
- using System.Linq.Expressions;
- #endif
- using System.ComponentModel;
- using System.Diagnostics.CodeAnalysis;
- #if SIMPLE_JSON_DYNAMIC
- using System.Dynamic;
- #endif
- using System.Globalization;
- using System.Reflection;
- using System.Runtime.Serialization;
- using System.Text;
- namespace SimpleJson
- {
-
-
-
-
- [EditorBrowsable(EditorBrowsableState.Never)]
- [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
- #if SIMPLE_JSON_OBJARRAYINTERNAL
- internal
- #else
- public
- #endif
- class JsonArray : List<object>
- {
-
-
-
- public JsonArray() { }
-
-
-
-
- public JsonArray(int capacity) : base(capacity) { }
-
-
-
-
- public override string ToString()
- {
- return SimpleJson.SerializeObject(this) ?? string.Empty;
- }
- }
-
-
-
-
- [EditorBrowsable(EditorBrowsableState.Never)]
- [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
- #if SIMPLE_JSON_OBJARRAYINTERNAL
- internal
- #else
- public
- #endif
- class JsonObject :
- #if SIMPLE_JSON_DYNAMIC
- DynamicObject,
- #endif
- IDictionary<string, object>
- {
-
-
-
- private readonly Dictionary<string, object> _members;
-
-
-
- public JsonObject()
- {
- _members = new Dictionary<string, object>();
- }
-
-
-
-
- public JsonObject(IEqualityComparer<string> comparer)
- {
- _members = new Dictionary<string, object>(comparer);
- }
-
-
-
-
- public object this[int index]
- {
- get { return GetAtIndex(_members, index); }
- }
- internal static object GetAtIndex(IDictionary<string, object> obj, int index)
- {
- if (obj == null)
- throw new ArgumentNullException("obj");
- if (index >= obj.Count)
- throw new ArgumentOutOfRangeException("index");
- int i = 0;
- foreach (KeyValuePair<string, object> o in obj)
- if (i++ == index) return o.Value;
- return null;
- }
-
-
-
-
-
- public void Add(string key, object value)
- {
- _members.Add(key, value);
- }
-
-
-
-
-
-
-
- public bool ContainsKey(string key)
- {
- return _members.ContainsKey(key);
- }
-
-
-
-
- public ICollection<string> Keys
- {
- get { return _members.Keys; }
- }
-
-
-
-
-
- public bool Remove(string key)
- {
- return _members.Remove(key);
- }
-
-
-
-
-
-
- public bool TryGetValue(string key, out object value)
- {
- try
- {
- return _members.TryGetValue(key, out value);
- }
- catch(Exception)
- {
- value = null;
- return false;
- }
- }
-
-
-
-
- public ICollection<object> Values
- {
- get { return _members.Values; }
- }
-
-
-
-
- public object this[string key]
- {
- get { return _members[key]; }
- set { _members[key] = value; }
- }
-
-
-
-
- public void Add(KeyValuePair<string, object> item)
- {
- _members.Add(item.Key, item.Value);
- }
-
-
-
- public void Clear()
- {
- _members.Clear();
- }
-
-
-
-
-
-
-
- public bool Contains(KeyValuePair<string, object> item)
- {
- return _members.ContainsKey(item.Key) && _members[item.Key] == item.Value;
- }
-
-
-
-
-
- public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
- {
- if (array == null) throw new ArgumentNullException("array");
- int num = Count;
- foreach (KeyValuePair<string, object> kvp in this)
- {
- array[arrayIndex++] = kvp;
- if (--num <= 0)
- return;
- }
- }
-
-
-
-
- public int Count
- {
- get { return _members.Count; }
- }
-
-
-
-
-
-
- public bool IsReadOnly
- {
- get { return false; }
- }
-
-
-
-
-
- public bool Remove(KeyValuePair<string, object> item)
- {
- return _members.Remove(item.Key);
- }
-
-
-
-
- public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
- {
- return _members.GetEnumerator();
- }
-
-
-
-
-
-
- IEnumerator IEnumerable.GetEnumerator()
- {
- return _members.GetEnumerator();
- }
-
-
-
-
-
-
- public override string ToString()
- {
- return SimpleJson.SerializeObject(this);
- }
- #if SIMPLE_JSON_DYNAMIC
-
-
-
-
-
-
-
-
- public override bool TryConvert(ConvertBinder binder, out object result)
- {
-
- if (binder == null)
- throw new ArgumentNullException("binder");
-
- Type targetType = binder.Type;
- if ((targetType == typeof(IEnumerable)) ||
- (targetType == typeof(IEnumerable<KeyValuePair<string, object>>)) ||
- (targetType == typeof(IDictionary<string, object>)) ||
- (targetType == typeof(IDictionary)))
- {
- result = this;
- return true;
- }
- return base.TryConvert(binder, out result);
- }
-
-
-
-
-
-
-
- public override bool TryDeleteMember(DeleteMemberBinder binder)
- {
-
- if (binder == null)
- throw new ArgumentNullException("binder");
-
- return _members.Remove(binder.Name);
- }
-
-
-
-
-
-
-
-
-
- public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
- {
- if (indexes == null) throw new ArgumentNullException("indexes");
- if (indexes.Length == 1)
- {
- result = ((IDictionary<string, object>)this)[(string)indexes[0]];
- return true;
- }
- result = null;
- return true;
- }
-
-
-
-
-
-
-
-
- public override bool TryGetMember(GetMemberBinder binder, out object result)
- {
- object value;
- if (_members.TryGetValue(binder.Name, out value))
- {
- result = value;
- return true;
- }
- result = null;
- return true;
- }
-
-
-
-
-
-
-
-
-
- public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
- {
- if (indexes == null) throw new ArgumentNullException("indexes");
- if (indexes.Length == 1)
- {
- ((IDictionary<string, object>)this)[(string)indexes[0]] = value;
- return true;
- }
- return base.TrySetIndex(binder, indexes, value);
- }
-
-
-
-
-
-
-
-
- public override bool TrySetMember(SetMemberBinder binder, object value)
- {
-
- if (binder == null)
- throw new ArgumentNullException("binder");
-
- _members[binder.Name] = value;
- return true;
- }
-
-
-
-
-
-
- public override IEnumerable<string> GetDynamicMemberNames()
- {
- foreach (var key in Keys)
- yield return key;
- }
- #endif
- }
- }
- namespace SimpleJson
- {
-
-
-
-
-
-
-
-
- #if SIMPLE_JSON_INTERNAL
- internal
- #else
- public
- #endif
- static class SimpleJson
- {
- private const int TOKEN_NONE = 0;
- private const int TOKEN_CURLY_OPEN = 1;
- private const int TOKEN_CURLY_CLOSE = 2;
- private const int TOKEN_SQUARED_OPEN = 3;
- private const int TOKEN_SQUARED_CLOSE = 4;
- private const int TOKEN_COLON = 5;
- private const int TOKEN_COMMA = 6;
- private const int TOKEN_STRING = 7;
- private const int TOKEN_NUMBER = 8;
- private const int TOKEN_TRUE = 9;
- private const int TOKEN_FALSE = 10;
- private const int TOKEN_NULL = 11;
- private const int BUILDER_CAPACITY = 2000;
- private static readonly char[] EscapeTable;
- private static readonly char[] EscapeCharacters = new char[] { '"', '\\', '\b', '\f', '\n', '\r', '\t' };
- private static readonly string EscapeCharactersString = new string(EscapeCharacters);
- static SimpleJson()
- {
- EscapeTable = new char[93];
- EscapeTable['"'] = '"';
- EscapeTable['\\'] = '\\';
- EscapeTable['\b'] = 'b';
- EscapeTable['\f'] = 'f';
- EscapeTable['\n'] = 'n';
- EscapeTable['\r'] = 'r';
- EscapeTable['\t'] = 't';
- }
-
-
-
-
-
- public static object DeserializeObject(string json)
- {
- object obj;
- if (TryDeserializeObject(json, out obj))
- return obj;
- return "Invalid JSON string";
-
- }
-
-
-
-
-
-
-
-
-
-
-
-
- [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification="Need to support .NET 2")]
- public static bool TryDeserializeObject(string json, out object obj)
- {
- bool success = true;
- if (json != null)
- {
- char[] charArray = json.ToCharArray();
- int index = 0;
- obj = ParseValue(charArray, ref index, ref success);
- }
- else
- obj = null;
- return success;
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public static string SerializeObject(object json, IJsonSerializerStrategy jsonSerializerStrategy)
- {
- StringBuilder builder = new StringBuilder(BUILDER_CAPACITY);
- bool success = SerializeValue(jsonSerializerStrategy, json, builder);
- return (success ? builder.ToString() : null);
- }
- public static string SerializeObject(object json)
- {
- return SerializeObject(json, CurrentJsonSerializerStrategy);
- }
- public static string EscapeToJavascriptString(string jsonString)
- {
- if (string.IsNullOrEmpty(jsonString))
- return jsonString;
- StringBuilder sb = new StringBuilder();
- char c;
- for (int i = 0; i < jsonString.Length; )
- {
- c = jsonString[i++];
- if (c == '\\')
- {
- int remainingLength = jsonString.Length - i;
- if (remainingLength >= 2)
- {
- char lookahead = jsonString[i];
- if (lookahead == '\\')
- {
- sb.Append('\\');
- ++i;
- }
- else if (lookahead == '"')
- {
- sb.Append("\"");
- ++i;
- }
- else if (lookahead == 't')
- {
- sb.Append('\t');
- ++i;
- }
- else if (lookahead == 'b')
- {
- sb.Append('\b');
- ++i;
- }
- else if (lookahead == 'n')
- {
- sb.Append('\n');
- ++i;
- }
- else if (lookahead == 'r')
- {
- sb.Append('\r');
- ++i;
- }
- }
- }
- else
- {
- sb.Append(c);
- }
- }
- return sb.ToString();
- }
- static IDictionary<string, object> ParseObject(char[] json, ref int index, ref bool success)
- {
- IDictionary<string, object> table = new JsonObject();
- int token;
-
- NextToken(json, ref index);
- bool done = false;
- while (!done)
- {
- token = LookAhead(json, index);
- if (token == TOKEN_NONE)
- {
- success = false;
- return null;
- }
- else if (token == TOKEN_COMMA)
- NextToken(json, ref index);
- else if (token == TOKEN_CURLY_CLOSE)
- {
- NextToken(json, ref index);
- return table;
- }
- else
- {
-
- string name = ParseString(json, ref index, ref success);
- if (!success)
- {
- success = false;
- return null;
- }
-
- token = NextToken(json, ref index);
- if (token != TOKEN_COLON)
- {
- success = false;
- return null;
- }
-
- object value = ParseValue(json, ref index, ref success);
- if (!success)
- {
- success = false;
- return null;
- }
- table[name] = value;
- }
- }
- return table;
- }
- static JsonArray ParseArray(char[] json, ref int index, ref bool success)
- {
- JsonArray array = new JsonArray();
-
- NextToken(json, ref index);
- bool done = false;
- while (!done)
- {
- int token = LookAhead(json, index);
- if (token == TOKEN_NONE)
- {
- success = false;
- return null;
- }
- else if (token == TOKEN_COMMA)
- NextToken(json, ref index);
- else if (token == TOKEN_SQUARED_CLOSE)
- {
- NextToken(json, ref index);
- break;
- }
- else
- {
- object value = ParseValue(json, ref index, ref success);
- if (!success)
- return null;
- array.Add(value);
- }
- }
- return array;
- }
- static object ParseValue(char[] json, ref int index, ref bool success)
- {
- switch (LookAhead(json, index))
- {
- case TOKEN_STRING:
- return ParseString(json, ref index, ref success);
- case TOKEN_NUMBER:
- return ParseNumber(json, ref index, ref success);
- case TOKEN_CURLY_OPEN:
- return ParseObject(json, ref index, ref success);
- case TOKEN_SQUARED_OPEN:
- return ParseArray(json, ref index, ref success);
- case TOKEN_TRUE:
- NextToken(json, ref index);
- return true;
- case TOKEN_FALSE:
- NextToken(json, ref index);
- return false;
- case TOKEN_NULL:
- NextToken(json, ref index);
- return null;
- case TOKEN_NONE:
- break;
- }
- success = false;
- return null;
- }
- static string ParseString(char[] json, ref int index, ref bool success)
- {
- StringBuilder s = new StringBuilder(BUILDER_CAPACITY);
- char c;
- EatWhitespace(json, ref index);
-
- c = json[index++];
- bool complete = false;
- while (!complete)
- {
- if (index == json.Length)
- break;
- c = json[index++];
- if (c == '"')
- {
- complete = true;
- break;
- }
- else if (c == '\\')
- {
- if (index == json.Length)
- break;
- c = json[index++];
- if (c == '"')
- s.Append('"');
- else if (c == '\\')
- s.Append('\\');
- else if (c == '/')
- s.Append('/');
- else if (c == 'b')
- s.Append('\b');
- else if (c == 'f')
- s.Append('\f');
- else if (c == 'n')
- s.Append('\n');
- else if (c == 'r')
- s.Append('\r');
- else if (c == 't')
- s.Append('\t');
- else if (c == 'u')
- {
- int remainingLength = json.Length - index;
- if (remainingLength >= 4)
- {
-
- uint codePoint;
- if (!(success = UInt32.TryParse(new string(json, index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint)))
- return "";
-
- if (0xD800 <= codePoint && codePoint <= 0xDBFF)
- {
- index += 4;
- remainingLength = json.Length - index;
- if (remainingLength >= 6)
- {
- uint lowCodePoint;
- if (new string(json, index, 2) == "\\u" && UInt32.TryParse(new string(json, index + 2, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out lowCodePoint))
- {
- if (0xDC00 <= lowCodePoint && lowCodePoint <= 0xDFFF)
- {
- s.Append((char)codePoint);
- s.Append((char)lowCodePoint);
- index += 6;
- continue;
- }
- }
- }
- success = false;
- return "";
- }
- s.Append(ConvertFromUtf32((int)codePoint));
-
- index += 4;
- }
- else
- break;
- }
- }
- else
- s.Append(c);
- }
- if (!complete)
- {
- success = false;
- return null;
- }
- return s.ToString();
- }
- private static string ConvertFromUtf32(int utf32)
- {
-
- if (utf32 < 0 || utf32 > 0x10FFFF)
- throw new ArgumentOutOfRangeException("utf32", "The argument must be from 0 to 0x10FFFF.");
- if (0xD800 <= utf32 && utf32 <= 0xDFFF)
- throw new ArgumentOutOfRangeException("utf32", "The argument must not be in surrogate pair range.");
- if (utf32 < 0x10000)
- return new string((char)utf32, 1);
- utf32 -= 0x10000;
- return new string(new char[] { (char)((utf32 >> 10) + 0xD800), (char)(utf32 % 0x0400 + 0xDC00) });
- }
- static object ParseNumber(char[] json, ref int index, ref bool success)
- {
- EatWhitespace(json, ref index);
- int lastIndex = GetLastIndexOfNumber(json, index);
- int charLength = (lastIndex - index) + 1;
- object returnNumber;
- string str = new string(json, index, charLength);
- if (str.IndexOf(".", StringComparison.OrdinalIgnoreCase) != -1 || str.IndexOf("e", StringComparison.OrdinalIgnoreCase) != -1)
- {
- double number;
- success = double.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);
- returnNumber = number;
- }
- else
- {
- long number;
- success = long.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);
- returnNumber = number;
- }
- index = lastIndex + 1;
- return returnNumber;
- }
- static int GetLastIndexOfNumber(char[] json, int index)
- {
- int lastIndex;
- for (lastIndex = index; lastIndex < json.Length; lastIndex++)
- if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) break;
- return lastIndex - 1;
- }
- static void EatWhitespace(char[] json, ref int index)
- {
- for (; index < json.Length; index++)
- if (" \t\n\r\b\f".IndexOf(json[index]) == -1) break;
- }
- static int LookAhead(char[] json, int index)
- {
- int saveIndex = index;
- return NextToken(json, ref saveIndex);
- }
- [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
- static int NextToken(char[] json, ref int index)
- {
- EatWhitespace(json, ref index);
- if (index == json.Length)
- return TOKEN_NONE;
- char c = json[index];
- index++;
- switch (c)
- {
- case '{':
- return TOKEN_CURLY_OPEN;
- case '}':
- return TOKEN_CURLY_CLOSE;
- case '[':
- return TOKEN_SQUARED_OPEN;
- case ']':
- return TOKEN_SQUARED_CLOSE;
- case ',':
- return TOKEN_COMMA;
- case '"':
- return TOKEN_STRING;
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- case '-':
- return TOKEN_NUMBER;
- case ':':
- return TOKEN_COLON;
- }
- index--;
- int remainingLength = json.Length - index;
-
- if (remainingLength >= 5)
- {
- if (json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e')
- {
- index += 5;
- return TOKEN_FALSE;
- }
- }
-
- if (remainingLength >= 4)
- {
- if (json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e')
- {
- index += 4;
- return TOKEN_TRUE;
- }
- }
-
- if (remainingLength >= 4)
- {
- if (json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l')
- {
- index += 4;
- return TOKEN_NULL;
- }
- }
- return TOKEN_NONE;
- }
- static bool SerializeValue(IJsonSerializerStrategy jsonSerializerStrategy, object value, StringBuilder builder)
- {
- bool success = true;
- string stringValue = value as string;
- if (stringValue != null)
- success = SerializeString(stringValue, builder);
- else
- {
- IDictionary<string, object> dict = value as IDictionary<string, object>;
- if (dict != null)
- {
- success = SerializeObject(jsonSerializerStrategy, dict.Keys, dict.Values, builder);
- }
- else
- {
- IDictionary<string, string> stringDictionary = value as IDictionary<string, string>;
- if (stringDictionary != null)
- {
- success = SerializeObject(jsonSerializerStrategy, stringDictionary.Keys, stringDictionary.Values, builder);
- }
- else
- {
- IEnumerable enumerableValue = value as IEnumerable;
- if (enumerableValue != null)
- success = SerializeArray(jsonSerializerStrategy, enumerableValue, builder);
- else if (IsNumeric(value))
- success = SerializeNumber(value, builder);
- else if (value is bool)
- builder.Append((bool)value ? "true" : "false");
- else if (value == null)
- builder.Append("null");
- else
- {
- object serializedObject;
- success = jsonSerializerStrategy.TrySerializeNonPrimitiveObject(value, out serializedObject);
- if (success)
- SerializeValue(jsonSerializerStrategy, serializedObject, builder);
- }
- }
- }
- }
- return success;
- }
- static bool SerializeObject(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable keys, IEnumerable values, StringBuilder builder)
- {
- builder.Append("{");
- IEnumerator ke = keys.GetEnumerator();
- IEnumerator ve = values.GetEnumerator();
- bool first = true;
- while (ke.MoveNext() && ve.MoveNext())
- {
- object key = ke.Current;
- object value = ve.Current;
- if (!first)
- builder.Append(",");
- string stringKey = key as string;
- if (stringKey != null)
- SerializeString(stringKey, builder);
- else
- if (!SerializeValue(jsonSerializerStrategy, value, builder)) return false;
- builder.Append(":");
- if (!SerializeValue(jsonSerializerStrategy, value, builder))
- return false;
- first = false;
- }
- builder.Append("}");
- return true;
- }
- static bool SerializeArray(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable anArray, StringBuilder builder)
- {
- builder.Append("[");
- bool first = true;
- foreach (object value in anArray)
- {
- if (!first)
- builder.Append(",");
- if (!SerializeValue(jsonSerializerStrategy, value, builder))
- return false;
- first = false;
- }
- builder.Append("]");
- return true;
- }
- static bool SerializeString(string aString, StringBuilder builder)
- {
-
- if (aString.IndexOfAny(EscapeCharacters) == -1)
- {
- builder.Append('"');
- builder.Append(aString);
- builder.Append('"');
- return true;
- }
- builder.Append('"');
- int safeCharacterCount = 0;
- char[] charArray = aString.ToCharArray();
- for (int i = 0; i < charArray.Length; i++)
- {
- char c = charArray[i];
-
-
-
- if (c >= EscapeTable.Length || EscapeTable[c] == default(char))
- {
- safeCharacterCount++;
- }
- else
- {
- if (safeCharacterCount > 0)
- {
- builder.Append(charArray, i - safeCharacterCount, safeCharacterCount);
- safeCharacterCount = 0;
- }
- builder.Append('\\');
- builder.Append(EscapeTable[c]);
- }
- }
- if (safeCharacterCount > 0)
- {
- builder.Append(charArray, charArray.Length - safeCharacterCount, safeCharacterCount);
- }
- builder.Append('"');
- return true;
- }
- static bool SerializeNumber(object number, StringBuilder builder)
- {
- if (number is long)
- builder.Append(((long)number).ToString(CultureInfo.InvariantCulture));
- else if (number is ulong)
- builder.Append(((ulong)number).ToString(CultureInfo.InvariantCulture));
- else if (number is int)
- builder.Append(((int)number).ToString(CultureInfo.InvariantCulture));
- else if (number is uint)
- builder.Append(((uint)number).ToString(CultureInfo.InvariantCulture));
- else if (number is decimal)
- builder.Append(((decimal)number).ToString(CultureInfo.InvariantCulture));
- else if (number is float)
- builder.Append(((float)number).ToString(CultureInfo.InvariantCulture));
- else
- builder.Append(Convert.ToDouble(number, CultureInfo.InvariantCulture).ToString("r", CultureInfo.InvariantCulture));
- return true;
- }
-
-
-
-
- static bool IsNumeric(object value)
- {
- if (value is sbyte) return true;
- if (value is byte) return true;
- if (value is short) return true;
- if (value is ushort) return true;
- if (value is int) return true;
- if (value is uint) return true;
- if (value is long) return true;
- if (value is ulong) return true;
- if (value is float) return true;
- if (value is double) return true;
- if (value is decimal) return true;
- return false;
- }
- private static IJsonSerializerStrategy _currentJsonSerializerStrategy;
- public static IJsonSerializerStrategy CurrentJsonSerializerStrategy
- {
- get
- {
- return _currentJsonSerializerStrategy ??
- (_currentJsonSerializerStrategy =
- #if SIMPLE_JSON_DATACONTRACT
- DataContractJsonSerializerStrategy
- #else
-
- MorefunJsonSerializerStrategy
- #endif
- );
- }
- set
- {
- _currentJsonSerializerStrategy = value;
- }
- }
-
-
-
-
-
-
-
-
-
- private static MorefunJsonSerializerStrategy _morefunJsonSerializerStrategy;
- [EditorBrowsable(EditorBrowsableState.Advanced)]
- public static MorefunJsonSerializerStrategy MorefunJsonSerializerStrategy
- {
- get
- {
- return _morefunJsonSerializerStrategy ?? (_morefunJsonSerializerStrategy = new MorefunJsonSerializerStrategy());
- }
- }
- #if SIMPLE_JSON_DATACONTRACT
- private static DataContractJsonSerializerStrategy _dataContractJsonSerializerStrategy;
- [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)]
- public static DataContractJsonSerializerStrategy DataContractJsonSerializerStrategy
- {
- get
- {
- return _dataContractJsonSerializerStrategy ?? (_dataContractJsonSerializerStrategy = new DataContractJsonSerializerStrategy());
- }
- }
- #endif
- }
-
-
- #if SIMPLE_JSON_INTERNAL
- internal
- #else
- public
- #endif
- interface IJsonSerializerStrategy
- {
- [SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate", Justification="Need to support .NET 2")]
- bool TrySerializeNonPrimitiveObject(object input, out object output);
- object DeserializeObject(object value, Type type);
- }
- public class MorefunJsonSerializerStrategy : IJsonSerializerStrategy
- {
- private static readonly string[] Iso8601Format = new string[]
- {
- @"yyyy-MM-dd\THH:mm:ss.FFFFFFF\Z",
- @"yyyy-MM-dd\THH:mm:ss\Z",
- @"yyyy-MM-dd\THH:mm:ssK"
- };
- protected virtual object SerializeEnum(Enum p)
- {
- return Convert.ToDouble(p, CultureInfo.InvariantCulture);
- }
- protected virtual string MapClrMemberNameToJsonFieldName(string clrPropertyName)
- {
- return clrPropertyName;
- }
- protected virtual bool TrySerializeUnknownTypes(object input, out object output)
- {
- if (input == null) throw new ArgumentNullException("input");
- output = null;
- Type type = input.GetType();
- if (type.FullName == null)
- return false;
- IDictionary<string, object> obj = new JsonObject();
-
- foreach (PropertyInfo info in type.GetProperties())
- {
- obj.Add(MapClrMemberNameToJsonFieldName(info.Name), info.GetGetMethod().Invoke(input, null));
-
- }
- output = obj;
- return true;
- }
- protected virtual bool TrySerializeKnownTypes(object input, out object output)
- {
- bool returnValue = true;
- if (input is DateTime)
- output = ((DateTime)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture);
- else if (input is DateTimeOffset)
- output = ((DateTimeOffset)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture);
- else if (input is Guid)
- output = ((Guid)input).ToString("D");
- else if (input is Uri)
- output = input.ToString();
- else
- {
- Enum inputEnum = input as Enum;
- if (inputEnum != null)
- output = SerializeEnum(inputEnum);
- else
- {
- returnValue = false;
- output = null;
- }
- }
- return returnValue;
- }
- public bool TrySerializeNonPrimitiveObject(object input, out object output)
- {
- return TrySerializeKnownTypes(input, out output) || TrySerializeUnknownTypes(input, out output);
- }
- public object DeserializeObject(object value, Type type)
- {
- return "";
- }
- }
-
-
-
-
- #if SIMPLE_JSON_DATACONTRACT
- [GeneratedCode("simple-json", "1.0.0")]
- #if SIMPLE_JSON_INTERNAL
- internal
- #else
- public
- #endif
- class DataContractJsonSerializerStrategy : PocoJsonSerializerStrategy
- {
- public DataContractJsonSerializerStrategy()
- {
- GetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, ReflectionUtils.GetDelegate>>(GetterValueFactory);
- SetCache = new ReflectionUtils.ThreadSafeDictionary<Type, IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>>(SetterValueFactory);
- }
- internal override IDictionary<string, ReflectionUtils.GetDelegate> GetterValueFactory(Type type)
- {
- bool hasDataContract = ReflectionUtils.GetAttribute(type, typeof(DataContractAttribute)) != null;
- if (!hasDataContract)
- return base.GetterValueFactory(type);
- string jsonKey;
- IDictionary<string, ReflectionUtils.GetDelegate> result = new Dictionary<string, ReflectionUtils.GetDelegate>();
- foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))
- {
- if (propertyInfo.CanRead)
- {
- MethodInfo getMethod = ReflectionUtils.GetGetterMethodInfo(propertyInfo);
- if (!getMethod.IsStatic && CanAdd(propertyInfo, out jsonKey))
- result[jsonKey] = ReflectionUtils.GetGetMethod(propertyInfo);
- }
- }
- foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))
- {
- if (!fieldInfo.IsStatic && CanAdd(fieldInfo, out jsonKey))
- result[jsonKey] = ReflectionUtils.GetGetMethod(fieldInfo);
- }
- return result;
- }
- internal override IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> SetterValueFactory(Type type)
- {
- bool hasDataContract = ReflectionUtils.GetAttribute(type, typeof(DataContractAttribute)) != null;
- if (!hasDataContract)
- return base.SetterValueFactory(type);
- string jsonKey;
- IDictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>> result = new Dictionary<string, KeyValuePair<Type, ReflectionUtils.SetDelegate>>();
- foreach (PropertyInfo propertyInfo in ReflectionUtils.GetProperties(type))
- {
- if (propertyInfo.CanWrite)
- {
- MethodInfo setMethod = ReflectionUtils.GetSetterMethodInfo(propertyInfo);
- if (!setMethod.IsStatic && CanAdd(propertyInfo, out jsonKey))
- result[jsonKey] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(propertyInfo.PropertyType, ReflectionUtils.GetSetMethod(propertyInfo));
- }
- }
- foreach (FieldInfo fieldInfo in ReflectionUtils.GetFields(type))
- {
- if (!fieldInfo.IsInitOnly && !fieldInfo.IsStatic && CanAdd(fieldInfo, out jsonKey))
- result[jsonKey] = new KeyValuePair<Type, ReflectionUtils.SetDelegate>(fieldInfo.FieldType, ReflectionUtils.GetSetMethod(fieldInfo));
- }
-
- return result;
- }
- private static bool CanAdd(MemberInfo info, out string jsonKey)
- {
- jsonKey = null;
- if (ReflectionUtils.GetAttribute(info, typeof(IgnoreDataMemberAttribute)) != null)
- return false;
- DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)ReflectionUtils.GetAttribute(info, typeof(DataMemberAttribute));
- if (dataMemberAttribute == null)
- return false;
- jsonKey = string.IsNullOrEmpty(dataMemberAttribute.Name) ? info.Name : dataMemberAttribute.Name;
- return true;
- }
- }
- #endif
- }
|