1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846 |
-
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.IO;
- using System.Reflection;
- using System.Globalization;
- using System.Collections;
- #if PETAJSON_DYNAMIC
- using System.Dynamic;
- #endif
- namespace PetaJson
- {
-
- [Flags]
- public enum JsonOptions
- {
- None = 0,
- WriteWhitespace = 0x00000001,
- DontWriteWhitespace = 0x00000002,
- StrictParser = 0x00000004,
- NonStrictParser = 0x00000008,
- }
-
- public static class Json
- {
- static Json()
- {
- WriteWhitespaceDefault = true;
- StrictParserDefault = false;
- }
-
- public static bool WriteWhitespaceDefault
- {
- get;
- set;
- }
-
- public static bool StrictParserDefault
- {
- get;
- set;
- }
-
- public static void Write(TextWriter w, object o, JsonOptions options = JsonOptions.None)
- {
- var writer = new Internal.Writer(w, ResolveOptions(options));
- writer.WriteValue(o);
- }
-
- public static void WriteFile(string filename, object o, JsonOptions options = JsonOptions.None)
- {
- using (var w = new StreamWriter(filename))
- {
- Write(w, o, options);
- }
- }
-
- public static string Format(object o, JsonOptions options = JsonOptions.None)
- {
- var sw = new StringWriter();
- var writer = new Internal.Writer(sw, ResolveOptions(options));
- writer.WriteValue(o);
- return sw.ToString();
- }
-
- public static object Parse(TextReader r, Type type, JsonOptions options = JsonOptions.None)
- {
- Internal.Reader reader = null;
- try
- {
- reader = new Internal.Reader(r, ResolveOptions(options));
- var retv = reader.Parse(type);
- reader.CheckEOF();
- return retv;
- }
- catch (Exception x)
- {
- throw new JsonParseException(x, reader==null ? new JsonLineOffset() : reader.CurrentTokenPosition);
- }
- }
-
- public static T Parse<T>(TextReader r, JsonOptions options = JsonOptions.None)
- {
- return (T)Parse(r, typeof(T), options);
- }
-
- public static void ParseInto(TextReader r, Object into, JsonOptions options = JsonOptions.None)
- {
- Internal.Reader reader = null;
- try
- {
- reader = new Internal.Reader(r, ResolveOptions(options));
- reader.ParseInto(into);
- reader.CheckEOF();
- }
- catch (Exception x)
- {
- throw new JsonParseException(x, reader==null ? new JsonLineOffset() : reader.CurrentTokenPosition);
- }
- }
-
- public static object ParseFile(string filename, Type type, JsonOptions options = JsonOptions.None)
- {
- using (var r = new StreamReader(filename))
- {
- return Parse(r, type, options);
- }
- }
-
- public static T ParseFile<T>(string filename, JsonOptions options = JsonOptions.None)
- {
- using (var r = new StreamReader(filename))
- {
- return Parse<T>(r, options);
- }
- }
-
- public static void ParseFileInto(string filename, Object into, JsonOptions options = JsonOptions.None)
- {
- using (var r = new StreamReader(filename))
- {
- ParseInto(r, into, options);
- }
- }
-
- public static object Parse(string data, Type type, JsonOptions options = JsonOptions.None)
- {
- return Parse(new StringReader(data), type, options);
- }
-
- public static T Parse<T>(string data, JsonOptions options = JsonOptions.None)
- {
- return (T)Parse<T>(new StringReader(data), options);
- }
-
- public static void ParseInto(string data, Object into, JsonOptions options = JsonOptions.None)
- {
- ParseInto(new StringReader(data), into, options);
- }
-
- public static T Clone<T>(T source)
- {
- return (T)Clone((object)source);
- }
-
- public static object Clone(object source)
- {
- if (source == null)
- return null;
- return Parse(Format(source), source.GetType());
- }
-
- public static void CloneInto<T>(T dest, T source)
- {
- ParseInto(Format(source), dest);
- }
-
- public static void RegisterFormatter(Type type, Action<IJsonWriter, object> formatter)
- {
- Internal.Writer._typeWriters[type] = formatter;
- }
-
- public static void RegisterFormatter<T>(Action<IJsonWriter, T> formatter)
- {
- RegisterFormatter(typeof(T), (w, o) => formatter(w, (T)o));
- }
-
- public static void RegisterParser(Type type, Func<IJsonReader, Type, object> parser)
- {
- Internal.Reader._typeReaders[type] = parser;
- }
-
- public static void RegisterParser<T>(Func<IJsonReader, Type, T> parser)
- {
- RegisterParser(typeof(T), (r, t) => parser(r, t));
- }
-
- public static void RegisterParser(Type type, Func<object, object> parser)
- {
- RegisterParser(type, (r, t) => r.ReadLiteral(parser));
- }
-
- public static void RegisterParser<T>(Func<object, T> parser)
- {
- RegisterParser(typeof(T), literal => parser(literal));
- }
-
-
-
- public static void RegisterTypeFactory(Type type, Func<IJsonReader, string, object> factory)
- {
- Internal.Reader._typeFactories[type] = factory;
- }
-
- static JsonOptions ResolveOptions(JsonOptions options)
- {
- JsonOptions resolved = JsonOptions.None;
- if ((options & (JsonOptions.WriteWhitespace|JsonOptions.DontWriteWhitespace))!=0)
- resolved |= options & (JsonOptions.WriteWhitespace | JsonOptions.DontWriteWhitespace);
- else
- resolved |= WriteWhitespaceDefault ? JsonOptions.WriteWhitespace : JsonOptions.DontWriteWhitespace;
- if ((options & (JsonOptions.StrictParser | JsonOptions.NonStrictParser)) != 0)
- resolved |= options & (JsonOptions.StrictParser | JsonOptions.NonStrictParser);
- else
- resolved |= StrictParserDefault ? JsonOptions.StrictParser : JsonOptions.NonStrictParser;
- return resolved;
- }
- }
-
- public interface IJsonLoading
- {
- void OnJsonLoading(IJsonReader r);
- }
-
- public interface IJsonLoaded
- {
- void OnJsonLoaded(IJsonReader r);
- }
-
-
- public interface IJsonLoadField
- {
- bool OnJsonField(IJsonReader r, string key);
- }
-
- public interface IJsonWriting
- {
- void OnJsonWriting(IJsonWriter w);
- }
-
- public interface IJsonWritten
- {
- void OnJsonWritten(IJsonWriter w);
- }
-
- public interface IJsonReader
- {
- object ReadLiteral(Func<object, object> converter);
- object Parse(Type type);
- T Parse<T>();
- void ReadDictionary(Action<string> callback);
- void ReadArray(Action callback);
- }
-
- public interface IJsonWriter
- {
- void WriteStringLiteral(string str);
- void WriteRaw(string str);
- void WriteArray(Action callback);
- void WriteDictionary(Action callback);
- void WriteValue(object value);
- void WriteElement();
- void WriteKey(string key);
- }
-
- public class JsonParseException : Exception
- {
- public JsonParseException(Exception inner, JsonLineOffset position) :
- base(string.Format("Json parse error at {0} - {1}", position, inner.Message), inner)
- {
- }
- }
-
- public struct JsonLineOffset
- {
- public int Line;
- public int Offset;
- public override string ToString()
- {
- return string.Format("line {0}, character {1}", Line + 1, Offset + 1);
- }
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field)]
- public class JsonAttribute : Attribute
- {
- public JsonAttribute()
- {
- _key = null;
- }
- public JsonAttribute(string key)
- {
- _key = key;
- }
-
- string _key;
- public string Key
- {
- get { return _key; }
- }
-
-
- public bool KeepInstance
- {
- get;
- set;
- }
- }
-
- [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
- public class JsonExcludeAttribute : Attribute
- {
- public JsonExcludeAttribute()
- {
- }
- }
- namespace Internal
- {
- public enum Token
- {
- EOF,
- Identifier,
- Literal,
- OpenBrace,
- CloseBrace,
- OpenSquare,
- CloseSquare,
- Equal,
- Colon,
- SemiColon,
- Comma,
- }
- public class Reader : IJsonReader
- {
- static Reader()
- {
- Func<IJsonReader, Type, object> simpleConverter = (reader, type) =>
- {
- return reader.ReadLiteral(literal => Convert.ChangeType(literal, type, CultureInfo.InvariantCulture));
- };
- _typeReaders.Add(typeof(string), simpleConverter);
- _typeReaders.Add(typeof(char), simpleConverter);
- _typeReaders.Add(typeof(bool), simpleConverter);
- _typeReaders.Add(typeof(byte), simpleConverter);
- _typeReaders.Add(typeof(sbyte), simpleConverter);
- _typeReaders.Add(typeof(short), simpleConverter);
- _typeReaders.Add(typeof(ushort), simpleConverter);
- _typeReaders.Add(typeof(int), simpleConverter);
- _typeReaders.Add(typeof(uint), simpleConverter);
- _typeReaders.Add(typeof(long), simpleConverter);
- _typeReaders.Add(typeof(ulong), simpleConverter);
- _typeReaders.Add(typeof(decimal), simpleConverter);
- _typeReaders.Add(typeof(float), simpleConverter);
- _typeReaders.Add(typeof(double), simpleConverter);
- _typeReaders.Add(typeof(DateTime), (reader, type) =>
- {
- return reader.ReadLiteral(literal => Utils.FromUnixMilliseconds((long)Convert.ChangeType(literal, typeof(long), CultureInfo.InvariantCulture)));
- });
- _typeReaders.Add(typeof(byte[]), (reader, type) =>
- {
- return reader.ReadLiteral(literal => Convert.FromBase64String((string)Convert.ChangeType(literal, typeof(string), CultureInfo.InvariantCulture)));
- });
- }
- public Reader(TextReader r, JsonOptions options)
- {
- _tokenizer = new Tokenizer(r, options);
- _options = options;
- }
- Tokenizer _tokenizer;
- JsonOptions _options;
- public JsonLineOffset CurrentTokenPosition
- {
- get { return _tokenizer.CurrentTokenPosition; }
- }
-
-
-
-
- public object ReadLiteral(Func<object, object> converter)
- {
- _tokenizer.Check(Token.Literal);
- var retv = converter(_tokenizer.Literal);
- _tokenizer.NextToken();
- return retv;
- }
- public void CheckEOF()
- {
- _tokenizer.Check(Token.EOF);
- }
- public object Parse(Type type)
- {
-
- if (_tokenizer.CurrentToken == Token.Literal && _tokenizer.Literal == null)
- {
- _tokenizer.NextToken();
- return null;
- }
-
- var typeUnderlying = Nullable.GetUnderlyingType(type);
- if (typeUnderlying != null)
- type = typeUnderlying;
-
- Func<IJsonReader, Type, object> typeReader;
- if (Reader._typeReaders.TryGetValue(type, out typeReader))
- {
- return typeReader(this, type);
- }
-
- if (type.IsEnum)
- {
- return ReadLiteral(literal => Enum.Parse(type, (string)literal));
- }
-
-
- Func<IJsonReader, string, object> typeFactory;
- if (Reader._typeFactories.TryGetValue(type, out typeFactory))
- {
-
- object into = typeFactory(this, null);
- if (into == null)
- {
-
-
-
-
-
-
-
- _tokenizer.CreateBookmark();
-
- _tokenizer.Skip(Token.OpenBrace);
-
- ReadDictionaryKeys(key =>
- {
-
- into = typeFactory(this, key);
- return into == null;
- });
-
- _tokenizer.RewindToBookmark();
-
- if (into == null)
- throw new InvalidOperationException("Factory didn't create object instance (probably due to a missing key in the Json)");
- }
-
- ParseInto(into);
-
- return into;
- }
-
- if (CanParseInto(type))
- {
- var into = Activator.CreateInstance(type);
- ParseInto(into);
- return into;
- }
-
- if (type.IsArray && type.GetArrayRank() == 1)
- {
-
- var listType = typeof(List<>).MakeGenericType(type.GetElementType());
- var list = Activator.CreateInstance(listType);
- ParseInto(list);
- return listType.GetMethod("ToArray").Invoke(list, null);
- }
-
- if (_tokenizer.CurrentToken == Token.OpenBrace && (type.IsAssignableFrom(typeof(Dictionary<string, object>))))
- {
- #if PETAJSON_DYNAMIC
- var container = (new ExpandoObject()) as IDictionary<string, object>;
- #else
- var container = new Dictionary<string, object>();
- #endif
- ReadDictionary(key =>
- {
- container[key] = Parse(typeof(Object));
- });
- return container;
- }
-
- if (_tokenizer.CurrentToken == Token.OpenSquare && (type.IsAssignableFrom(typeof(List<object>))))
- {
- var container = new List<object>();
- ReadArray(() =>
- {
- container.Add(Parse(typeof(Object)));
- });
- return container;
- }
-
- if (_tokenizer.CurrentToken == Token.Literal && type.IsAssignableFrom(_tokenizer.Literal.GetType()))
- {
- var lit = _tokenizer.Literal;
- _tokenizer.NextToken();
- return lit;
- }
- throw new InvalidDataException(string.Format("syntax error - unexpected token {0}", _tokenizer.CurrentToken));
- }
- public static bool CanParseInto(Type type)
- {
-
- if (type.IsArray)
- return false;
- if (typeof(IDictionary).IsAssignableFrom(type))
- return true;
- if (typeof(IList).IsAssignableFrom(type))
- return true;
- if (ReflectionInfo.GetReflectionInfo(type) != null)
- return true;
- return false;
- }
- public void ParseInto(object into)
- {
- if (TryParseInto(into))
- return;
- throw new InvalidOperationException(string.Format("Don't know how to load into '{0}'", into.GetType().FullName));
- }
- public Type FindGenericInterface(Type type, Type tItf)
- {
- foreach (var t in type.GetInterfaces())
- {
-
- if (t.IsGenericType && t.GetGenericTypeDefinition() == tItf)
- return type;
- }
- return null;
- }
- public bool TryParseInto(object into)
- {
- if (into == null)
- return false;
- var type = into.GetType();
-
- var dictType = FindGenericInterface(type, typeof(IDictionary<,>));
- if (dictType!=null)
- {
-
- var typeKey = dictType.GetGenericArguments()[0];
- var typeValue = dictType.GetGenericArguments()[1];
-
- IDictionary dict = (IDictionary)into;
- dict.Clear();
- ReadDictionary(key =>
- {
- dict.Add(Convert.ChangeType(key, typeKey), Parse(typeValue));
- });
- return true;
- }
-
- var listType = FindGenericInterface(type, typeof(IList<>));
- if (listType!=null)
- {
-
- var typeElement = listType.GetGenericArguments()[0];
-
- IList list = (IList)into;
- list.Clear();
- ReadArray(() =>
- {
- list.Add(Parse(typeElement));
- });
- return true;
- }
-
- var objDict = into as IDictionary;
- if (objDict != null)
- {
- objDict.Clear();
- ReadDictionary(key =>
- {
- objDict[key] = Parse(typeof(Object));
- });
- return true;
- }
-
- var objList = into as IList;
- if (objList!=null)
- {
- objList.Clear();
- ReadArray(() =>
- {
- objList.Add(Parse(typeof(Object)));
- });
- return true;
- }
-
- var ri = ReflectionInfo.GetReflectionInfo(type);
- if (ri != null)
- {
- ri.ParseInto(this, into);
- return true;
- }
- return false;
- }
- public T Parse<T>()
- {
- return (T)Parse(typeof(T));
- }
- public void ReadDictionary(Action<string> callback)
- {
- _tokenizer.Skip(Token.OpenBrace);
- ReadDictionaryKeys(key => { callback(key); return true; });
- _tokenizer.Skip(Token.CloseBrace);
- }
- private void ReadDictionaryKeys(Func<string, bool> callback)
- {
- while (_tokenizer.CurrentToken != Token.CloseBrace)
- {
-
- string key = null;
- if (_tokenizer.CurrentToken == Token.Identifier && (_options & JsonOptions.StrictParser)==0)
- {
- key = _tokenizer.String;
- }
- else if (_tokenizer.CurrentToken == Token.Literal && _tokenizer.Literal is String)
- {
- key = (string)_tokenizer.Literal;
- }
- else
- {
- throw new InvalidDataException("syntax error, expected string literal or identifier");
- }
- _tokenizer.NextToken();
- _tokenizer.Skip(Token.Colon);
- _tokenizer.DidMove = false;
- if (!callback(key))
- return;
- if (!_tokenizer.DidMove)
- {
-
- Parse(typeof(object));
- }
- if (_tokenizer.SkipIf(Token.Comma))
- {
- if ((_options & JsonOptions.StrictParser) != 0 && _tokenizer.CurrentToken == Token.CloseBrace)
- {
- throw new InvalidDataException("Trailing commas not allowed in strict mode");
- }
- continue;
- }
- break;
- }
- }
- public void ReadArray(Action callback)
- {
- _tokenizer.Skip(Token.OpenSquare);
- while (_tokenizer.CurrentToken != Token.CloseSquare)
- {
- callback();
- if (_tokenizer.SkipIf(Token.Comma))
- {
- if ((_options & JsonOptions.StrictParser)!=0 && _tokenizer.CurrentToken==Token.CloseSquare)
- {
- throw new InvalidDataException("Trailing commas not allowed in strict mode");
- }
- continue;
- }
- break;
- }
- _tokenizer.Skip(Token.CloseSquare);
- }
- public static Dictionary<Type, Func<IJsonReader, Type, object>> _typeReaders = new Dictionary<Type, Func<IJsonReader, Type, object>>();
- public static Dictionary<Type, Func<IJsonReader, string, object>> _typeFactories = new Dictionary<Type, Func<IJsonReader, string, object>>();
- }
- public class Writer : IJsonWriter
- {
- static Writer()
- {
-
- _typeWriters.Add(typeof(string), (w, o) => w.WriteStringLiteral((string)o));
- _typeWriters.Add(typeof(char), (w, o) => w.WriteStringLiteral(((char)o).ToString()));
-
- _typeWriters.Add(typeof(bool), (w, o) => w.WriteRaw(((bool)o) ? "true" : "false"));
-
- Action<IJsonWriter, object> convertWriter = (w, o) => w.WriteRaw((string)Convert.ChangeType(o, typeof(string), System.Globalization.CultureInfo.InvariantCulture));
- _typeWriters.Add(typeof(int), convertWriter);
- _typeWriters.Add(typeof(uint), convertWriter);
- _typeWriters.Add(typeof(long), convertWriter);
- _typeWriters.Add(typeof(ulong), convertWriter);
- _typeWriters.Add(typeof(short), convertWriter);
- _typeWriters.Add(typeof(ushort), convertWriter);
- _typeWriters.Add(typeof(decimal), convertWriter);
- _typeWriters.Add(typeof(byte), convertWriter);
- _typeWriters.Add(typeof(sbyte), convertWriter);
-
- _typeWriters.Add(typeof(DateTime), (w, o) => convertWriter(w, Utils.ToUnixMilliseconds((DateTime)o)));
-
- _typeWriters.Add(typeof(float), (w, o) => w.WriteRaw(((float)o).ToString("R", System.Globalization.CultureInfo.InvariantCulture)));
- _typeWriters.Add(typeof(double), (w, o) => w.WriteRaw(((double)o).ToString("R", System.Globalization.CultureInfo.InvariantCulture)));
-
- _typeWriters.Add(typeof(byte[]), (w, o) =>
- {
- w.WriteRaw("\"");
- w.WriteRaw(Convert.ToBase64String((byte[])o));
- w.WriteRaw("\"");
- });
- }
- public static Dictionary<Type, Action<IJsonWriter, object>> _typeWriters = new Dictionary<Type, Action<IJsonWriter, object>>();
- public Writer(TextWriter w, JsonOptions options)
- {
- _writer = w;
- _atStartOfLine = true;
- _needElementSeparator = false;
- _options = options;
- }
- TextWriter _writer;
- public int IndentLevel;
- bool _atStartOfLine;
- bool _needElementSeparator = false;
- JsonOptions _options;
- char _currentBlockKind = '\0';
- public void NextLine()
- {
- if (_atStartOfLine)
- return;
- if ((_options & JsonOptions.WriteWhitespace)!=0)
- {
- WriteRaw("\n");
- WriteRaw(new string('\t', IndentLevel));
- }
- _atStartOfLine = true;
- }
- void NextElement()
- {
- if (_needElementSeparator)
- {
- WriteRaw(",");
- NextLine();
- }
- else
- {
- NextLine();
- IndentLevel++;
- WriteRaw(_currentBlockKind.ToString());
- NextLine();
- }
- _needElementSeparator = true;
- }
- public void WriteElement()
- {
- if (_currentBlockKind != '[')
- throw new InvalidOperationException("Attempt to write array element when not in array block");
- NextElement();
- }
- public void WriteKey(string key)
- {
- if (_currentBlockKind != '{')
- throw new InvalidOperationException("Attempt to write dictionary element when not in dictionary block");
- NextElement();
- WriteStringLiteral(key);
- WriteRaw(((_options & JsonOptions.WriteWhitespace)!=0) ? ": " : ":");
- }
- public void WriteRaw(string str)
- {
- _atStartOfLine = false;
- _writer.Write(str);
- }
- public void WriteStringLiteral(string str)
- {
- _writer.Write("\"");
- foreach (var ch in str)
- {
- switch (ch)
- {
- case '\"': _writer.Write("\\\""); break;
- case '\r': _writer.Write("\\r"); break;
- case '\n': _writer.Write("\\n"); break;
- case '\t': _writer.Write("\\t"); break;
- case '\0': _writer.Write("\\0"); break;
- case '\\': _writer.Write("\\\\"); break;
- case '\'': _writer.Write("\\'"); break;
- default: _writer.Write(ch); break;
- }
- }
- _writer.Write("\"");
- }
- void WriteBlock(string open, string close, Action callback)
- {
- var prevBlockKind = _currentBlockKind;
- _currentBlockKind = open[0];
- var didNeedElementSeparator = _needElementSeparator;
- _needElementSeparator = false;
- callback();
- if (_needElementSeparator)
- {
- IndentLevel--;
- NextLine();
- }
- else
- {
- WriteRaw(open);
- }
- WriteRaw(close);
- _needElementSeparator = didNeedElementSeparator;
- _currentBlockKind = prevBlockKind;
- }
- public void WriteArray(Action callback)
- {
- WriteBlock("[", "]", callback);
- }
- public void WriteDictionary(Action callback)
- {
- WriteBlock("{", "}", callback);
- }
- public void WriteValue(object value)
- {
-
- if (value == null)
- {
- _writer.Write("null");
- return;
- }
- var type = value.GetType();
-
- var typeUnderlying = Nullable.GetUnderlyingType(type);
- if (typeUnderlying != null)
- type = typeUnderlying;
-
- Action<IJsonWriter, object> typeWriter;
- if (_typeWriters.TryGetValue(type, out typeWriter))
- {
-
- typeWriter(this, value);
- return;
- }
-
- if (type.IsEnum)
- {
- WriteStringLiteral(value.ToString());
- return;
- }
-
- var d = value as System.Collections.IDictionary;
- if (d != null)
- {
- WriteDictionary(() =>
- {
- foreach (var key in d.Keys)
- {
- WriteKey(key.ToString());
- WriteValue(d[key]);
- }
- });
- return;
- }
-
- var e = value as System.Collections.IEnumerable;
- if (e != null)
- {
- WriteArray(() =>
- {
- foreach (var i in e)
- {
- WriteElement();
- WriteValue(i);
- }
- });
- return;
- }
-
- var ri = ReflectionInfo.GetReflectionInfo(type);
- if (ri != null)
- {
- ri.Write(this, value);
- return;
- }
-
- throw new InvalidDataException(string.Format("Don't know how to write '{0}' to json", value.GetType()));
- }
- }
- class JsonMemberInfo
- {
- public MemberInfo Member;
- public string JsonKey;
- public bool KeepInstance;
- public Type MemberType
- {
- get
- {
- if (Member is PropertyInfo)
- {
- return ((PropertyInfo)Member).PropertyType;
- }
- else
- {
- return ((FieldInfo)Member).FieldType;
- }
- }
- }
- public void SetValue(object target, object value)
- {
- if (Member is PropertyInfo)
- {
- ((PropertyInfo)Member).SetValue(target, value, null);
- }
- else
- {
- ((FieldInfo)Member).SetValue(target, value);
- }
- }
- public object GetValue(object target)
- {
- if (Member is PropertyInfo)
- {
- return ((PropertyInfo)Member).GetValue(target, null);
- }
- else
- {
- return ((FieldInfo)Member).GetValue(target);
- }
- }
- }
- class ReflectionInfo
- {
- List<JsonMemberInfo> _members;
- static Dictionary<Type, ReflectionInfo> _cache = new Dictionary<Type, ReflectionInfo>();
- public void Write(Writer w, object val)
- {
- w.WriteDictionary(() =>
- {
- var writing = val as IJsonWriting;
- if (writing != null)
- writing.OnJsonWriting(w);
- foreach (var jmi in _members)
- {
- w.WriteKey(jmi.JsonKey);
- w.WriteValue(jmi.GetValue(val));
- }
- var written = val as IJsonWritten;
- if (written != null)
- written.OnJsonWritten(w);
- });
- }
-
-
-
-
-
-
- int _lastFoundIndex = 0;
- bool FindMemberInfo(string name, out JsonMemberInfo found)
- {
- for (int i = 0; i < _members.Count; i++)
- {
- int index = (i + _lastFoundIndex) % _members.Count;
- var jmi = _members[index];
- if (jmi.JsonKey == name)
- {
- _lastFoundIndex = index;
- found = jmi;
- return true;
- }
- }
- found = null;
- return false;
- }
- public void ParseFieldOrProperty(Reader r, object into, string key)
- {
- var lf = into as IJsonLoadField;
- if (lf != null)
- {
- if (lf.OnJsonField(r, key))
- return;
- }
- JsonMemberInfo jmi;
- if (FindMemberInfo(key, out jmi))
- {
- if (jmi.KeepInstance && Reader.CanParseInto(jmi.MemberType))
- {
- var subInto = jmi.GetValue(into);
- if (subInto != null)
- {
- r.ParseInto(subInto);
- return;
- }
- }
- var val = r.Parse(jmi.MemberType);
- jmi.SetValue(into, val);
- return;
- }
- }
- public void ParseInto(Reader r, object into)
- {
- var loading = into as IJsonLoading;
- r.ReadDictionary(key => {
- if (loading != null)
- {
- loading.OnJsonLoading(r);
- loading = null;
- }
-
- ParseFieldOrProperty(r, into, key);
- });
- var loaded = into as IJsonLoaded;
- if (loaded != null)
- loaded.OnJsonLoaded(r);
- }
- public static ReflectionInfo GetReflectionInfo(Type type)
- {
-
- ReflectionInfo existing;
- if (_cache.TryGetValue(type, out existing))
- return existing;
-
- bool typeMarked = type.GetCustomAttributes(typeof(JsonAttribute), true).OfType<JsonAttribute>().Any();
-
- bool anyFieldsMarked = GetAllFieldsAndProperties(type).Any(x => x.GetCustomAttributes(typeof(JsonAttribute), false).OfType<JsonAttribute>().Any());
-
- bool serializeAllPublics = typeMarked || !anyFieldsMarked;
-
- var ri = CreateReflectionInfo(type, mi =>
- {
-
- if (mi.GetCustomAttributes(typeof(JsonExcludeAttribute), false).OfType<JsonExcludeAttribute>().Any())
- return null;
-
- var attr = mi.GetCustomAttributes(typeof(JsonAttribute), false).OfType<JsonAttribute>().FirstOrDefault();
- if (attr != null)
- {
- return new JsonMemberInfo()
- {
- Member = mi,
- JsonKey = attr.Key ?? mi.Name.Substring(0, 1).ToLower() + mi.Name.Substring(1),
- KeepInstance = attr.KeepInstance,
- };
- }
-
- if (serializeAllPublics && IsPublic(mi))
- {
- return new JsonMemberInfo()
- {
- Member = mi,
- JsonKey = mi.Name.Substring(0, 1).ToLower() + mi.Name.Substring(1),
- };
- }
- return null;
- });
-
- _cache[type] = ri;
- return ri;
- }
- static bool IsPublic(MemberInfo mi)
- {
-
- var fi = mi as FieldInfo;
- if (fi!=null)
- return fi.IsPublic;
-
-
- var pi = mi as PropertyInfo;
- if (pi != null)
- {
- var gm = pi.GetGetMethod();
- return (gm != null && gm.IsPublic);
- }
- return false;
- }
- public static ReflectionInfo CreateReflectionInfo(Type type, Func<MemberInfo, JsonMemberInfo> callback)
- {
-
- ReflectionInfo existing;
- if (_cache.TryGetValue(type, out existing))
- return existing;
-
- var members = GetAllFieldsAndProperties(type).Select(x => callback(x)).Where(x => x != null).ToList();
-
- if (!members.Any())
- return null;
-
- var ri = new ReflectionInfo()
- {
- _members = members,
- };
- return ri;
- }
- static IEnumerable<MemberInfo> GetAllFieldsAndProperties(Type t)
- {
- if (t == null)
- return Enumerable.Empty<FieldInfo>();
- BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly;
- return t.GetMembers(flags).Where(x => x is FieldInfo || x is PropertyInfo).Concat(GetAllFieldsAndProperties(t.BaseType));
- }
- }
- internal static class Utils
- {
- public static long ToUnixMilliseconds(DateTime This)
- {
- return (long)This.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds;
- }
- public static DateTime FromUnixMilliseconds(long timeStamp)
- {
- return new DateTime(1970, 1, 1).AddMilliseconds(timeStamp);
- }
- }
- public class RewindableTextReader
- {
- public RewindableTextReader(TextReader underlying)
- {
- _underlying = underlying;
- ReadUnderlying();
- }
- TextReader _underlying;
- char[] _buf = new char[1024];
- int _pos;
- int _bufUsed;
- StringBuilder _rewindBuffer;
- int _rewindBufferPos;
- void ReadUnderlying()
- {
- _bufUsed = _underlying.Read(_buf, 0, _buf.Length);
- _pos = 0;
- }
- char ReadUnderlyingChar()
- {
- if (_pos >= _bufUsed)
- {
- if (_bufUsed > 0)
- {
- ReadUnderlying();
- }
- if (_bufUsed == 0)
- {
- return '\0';
- }
- }
-
- return _buf[_pos++];
- }
- public char ReadChar()
- {
- if (_rewindBuffer == null)
- return ReadUnderlyingChar();
- if (_rewindBufferPos < _rewindBuffer.Length)
- {
- return _rewindBuffer[_rewindBufferPos++];
- }
- else
- {
- char ch = ReadUnderlyingChar();
- _rewindBuffer.Append(ch);
- _rewindBufferPos++;
- return ch;
- }
- }
- Stack<int> _bookmarks = new Stack<int>();
- public void CreateBookmark()
- {
- if (_rewindBuffer == null)
- {
- _rewindBuffer = new StringBuilder();
- _rewindBufferPos = 0;
- }
- _bookmarks.Push(_rewindBufferPos);
- }
- public void RewindToBookmark()
- {
- _rewindBufferPos = _bookmarks.Pop();
- }
- public void DiscardBookmark()
- {
- _bookmarks.Pop();
- if (_bookmarks.Count == 0)
- {
- _rewindBuffer = null;
- _rewindBufferPos = 0;
- }
- }
- }
- public class Tokenizer
- {
- public Tokenizer(TextReader r, JsonOptions options)
- {
- _reader = new RewindableTextReader(r);
- _options = options;
- _state._nextCharPos.Line = 0;
- _state._nextCharPos.Offset = 0;
- _state._currentCharPos = _state._nextCharPos;
-
- NextChar();
- NextToken();
- }
- RewindableTextReader _reader;
- JsonOptions _options;
- StringBuilder _sb = new StringBuilder();
- ReaderState _state;
-
-
-
- struct ReaderState
- {
- public JsonLineOffset _nextCharPos;
- public JsonLineOffset _currentCharPos;
- public JsonLineOffset _currentTokenPos;
- public char _currentChar;
- public char _pendingChar;
- public Token _currentToken;
- public string _string;
- public object _literal;
- }
- Stack<ReaderState> _bookmarks = new Stack<ReaderState>();
- public void CreateBookmark()
- {
- _bookmarks.Push(_state);
- _reader.CreateBookmark();
- }
- public void DiscardBookmark()
- {
- _bookmarks.Pop();
- _reader.DiscardBookmark();
- }
- public void RewindToBookmark()
- {
- _state = _bookmarks.Pop();
- _reader.RewindToBookmark();
- }
- char NextChar()
- {
-
- char ch;
- if (_state._pendingChar != '\0')
- {
- ch = _state._pendingChar;
- }
- else
- {
- ch = _reader.ReadChar();
- if (ch == '\r')
- {
- ch = _reader.ReadChar();
- if (ch != '\n')
- {
- _state._pendingChar = ch;
- ch = '\n';
- }
- }
- }
- _state._currentCharPos = _state._nextCharPos;
-
- if (ch == '\n')
- {
- _state._nextCharPos.Line++;
- _state._nextCharPos.Offset = 0;
- }
- else
- {
- _state._nextCharPos.Offset++;
- }
- return _state._currentChar = ch;
- }
- public bool DidMove
- {
- get;
- set;
- }
- public void NextToken()
- {
- DidMove = true;
- _sb.Length = 0;
- State state = State.Initial;
- _state._currentTokenPos = _state._currentCharPos;
- while (true)
- {
- switch (state)
- {
- case State.Initial:
- if (IsIdentifierLeadChar(_state._currentChar))
- {
- state = State.Identifier;
- break;
- }
- else if (char.IsDigit(_state._currentChar) || _state._currentChar == '-')
- {
- TokenizeNumber();
- _state._currentToken = Token.Literal;
- return;
- }
- else if (char.IsWhiteSpace(_state._currentChar))
- {
- NextChar();
- _state._currentTokenPos = _state._currentCharPos;
- break;
- }
- switch (_state._currentChar)
- {
- case '/':
- if ((_options & JsonOptions.StrictParser)!=0)
- {
-
- throw new InvalidDataException(string.Format("syntax error - unexpected character '{0}'", _state._currentChar));
- }
- else
- {
- NextChar();
- state = State.Slash;
- }
- break;
- case '\"':
- NextChar();
- _sb.Length = 0;
- state = State.QuotedString;
- break;
- case '\'':
- NextChar();
- _sb.Length = 0;
- state = State.QuotedChar;
- break;
- case '\0':
- _state._currentToken = Token.EOF;
- return;
- case '{': _state._currentToken = Token.OpenBrace; NextChar(); return;
- case '}': _state._currentToken = Token.CloseBrace; NextChar(); return;
- case '[': _state._currentToken = Token.OpenSquare; NextChar(); return;
- case ']': _state._currentToken = Token.CloseSquare; NextChar(); return;
- case '=': _state._currentToken = Token.Equal; NextChar(); return;
- case ':': _state._currentToken = Token.Colon; NextChar(); return;
- case ';': _state._currentToken = Token.SemiColon; NextChar(); return;
- case ',': _state._currentToken = Token.Comma; NextChar(); return;
- default:
- throw new InvalidDataException(string.Format("syntax error - unexpected character '{0}'", _state._currentChar));
- }
- break;
- case State.Slash:
- switch (_state._currentChar)
- {
- case '/':
- NextChar();
- state = State.SingleLineComment;
- break;
- case '*':
- NextChar();
- state = State.BlockComment;
- break;
- default:
- throw new InvalidDataException("syntax error - unexpected character after slash");
- }
- break;
- case State.SingleLineComment:
- if (_state._currentChar == '\r' || _state._currentChar == '\n')
- {
- state = State.Initial;
- }
- NextChar();
- break;
- case State.BlockComment:
- if (_state._currentChar == '*')
- {
- NextChar();
- if (_state._currentChar == '/')
- {
- state = State.Initial;
- }
- }
- NextChar();
- break;
- case State.Identifier:
- if (IsIdentifierChar(_state._currentChar))
- {
- _sb.Append(_state._currentChar);
- NextChar();
- }
- else
- {
- _state._string = _sb.ToString();
- switch (this.String)
- {
- case "true":
- _state._literal = true;
- _state._currentToken = Token.Literal;
- break;
- case "false":
- _state._literal = false;
- _state._currentToken = Token.Literal;
- break;
- case "null":
- _state._literal = null;
- _state._currentToken = Token.Literal;
- break;
- default:
- _state._currentToken = Token.Identifier;
- break;
- }
- return;
- }
- break;
- case State.QuotedString:
- if (_state._currentChar == '\\')
- {
- AppendSpecialChar();
- }
- else if (_state._currentChar == '\"')
- {
- _state._literal = _sb.ToString();
- _state._currentToken = Token.Literal;
- NextChar();
- return;
- }
- else
- {
- _sb.Append(_state._currentChar);
- NextChar();
- continue;
- }
- break;
- case State.QuotedChar:
- if (_state._currentChar == '\\')
- {
- AppendSpecialChar();
- }
- else if (_state._currentChar == '\'')
- {
- _state._literal = _sb.ToString();
- _state._currentToken = Token.Literal;
- NextChar();
- return;
- }
- else
- {
- _sb.Append(_state._currentChar);
- NextChar();
- continue;
- }
- break;
- }
- }
- }
- void TokenizeNumber()
- {
- _sb.Length = 0;
-
- bool signed = false;
- if (_state._currentChar == '-')
- {
- signed = true;
- _sb.Append(_state._currentChar);
- NextChar();
- if (!Char.IsDigit(_state._currentChar))
- {
- throw new InvalidDataException("syntax error - expected digit to follow negative sign");
- }
- }
-
- bool fp = false;
- while (char.IsDigit(_state._currentChar) || _state._currentChar == '.' || _state._currentChar == 'e' || _state._currentChar == 'E' || _state._currentChar == 'x' || _state._currentChar == 'X')
- {
- if (_state._currentChar == 'e' || _state._currentChar == 'E')
- {
- fp = true;
- _sb.Append(_state._currentChar);
- NextChar();
- if (_state._currentChar == '-' || _state._currentChar == '+')
- {
- _sb.Append(_state._currentChar);
- NextChar();
- }
- }
- else
- {
- if (_state._currentChar == '.')
- fp = true;
- _sb.Append(_state._currentChar);
- NextChar();
- }
- }
- Type type = fp ? typeof(double) : (signed ? typeof(long) : typeof(ulong));
- if (char.IsLetterOrDigit(_state._currentChar))
- throw new InvalidDataException(string.Format("syntax error - invalid character following number '{0}'", _state._currentChar));
-
- try
- {
- _state._literal = Convert.ChangeType(_sb.ToString(), type, System.Globalization.CultureInfo.InvariantCulture);
- }
- catch
- {
- throw new InvalidDataException(string.Format("syntax error - incorrectly formatted number '{0}'", _sb.ToString()));
- }
- }
- public void Check(Token tokenRequired)
- {
- if (tokenRequired != CurrentToken)
- {
- throw new InvalidDataException(string.Format("syntax error - expected {0} found {1}", tokenRequired, CurrentToken));
- }
- }
- public void Skip(Token tokenRequired)
- {
- Check(tokenRequired);
- NextToken();
- }
- public bool SkipIf(Token tokenRequired)
- {
- if (tokenRequired == CurrentToken)
- {
- NextToken();
- return true;
- }
- return false;
- }
- void AppendSpecialChar()
- {
- NextChar();
- var escape = _state._currentChar;
- NextChar();
- switch (escape)
- {
- case '\'': _sb.Append('\''); break;
- case '\"': _sb.Append('\"'); break;
- case '\\': _sb.Append('\\'); break;
- case 'r': _sb.Append('\r'); break;
- case 'n': _sb.Append('\n'); break;
- case 't': _sb.Append('\t'); break;
- case '0': _sb.Append('\0'); break;
- case 'u':
- var sbHex = new StringBuilder();
- for (int i = 0; i < 4; i++)
- {
- sbHex.Append(_state._currentChar);
- NextChar();
- }
- _sb.Append((char)Convert.ToUInt16(sbHex.ToString(), 16));
- break;
- default:
- throw new InvalidDataException(string.Format("Invalid escape sequence in string literal: '\\{0}'", _state._currentChar));
- }
- }
- public Token CurrentToken
- {
- get { return _state._currentToken; }
- }
- public JsonLineOffset CurrentTokenPosition
- {
- get { return _state._currentTokenPos; }
- }
- public string String
- {
- get { return _state._string; }
- }
- public object Literal
- {
- get { return _state._literal; }
- }
- private enum State
- {
- Initial,
- Slash,
- SingleLineComment,
- BlockComment,
- Identifier,
- QuotedString,
- QuotedChar,
- }
- public static bool IsIdentifierChar(char ch)
- {
- return Char.IsLetterOrDigit(ch) || ch == '_' || ch == '$';
- }
- public static bool IsIdentifierLeadChar(char ch)
- {
- return Char.IsLetter(ch) || ch == '_' || ch == '$';
- }
- public static bool IsIdentifier(string str)
- {
- return IsIdentifierLeadChar(str[0]) && str.All(x => IsIdentifierChar(x));
- }
- }
- }
- }
|