Beispiel #1
0
        public void Rowset_FromJSON_DefMissed(bool rowsAsMap)
        {
            var row = new Person {
                Name = "Henry", Age = 43
            };
            var rowSet = new Rowset(row.Schema);

            rowSet.Add(row);
            var options = new Azos.Serialization.JSON.JSONWritingOptions
            {
                RowsetMetadata = true,
                RowsAsMap      = rowsAsMap
            };
            var json   = rowSet.ToJSON(options);
            var map    = JSONReader.DeserializeDataObject(json) as JSONDataMap;
            var schema = (map["Schema"] as IDictionary <string, object>);
            var defs   = schema["FieldDefs"] as IList <object>;

            defs.RemoveAt(1);

            bool allMatched;
            var  trg = RowsetBase.FromJSON(map, out allMatched);

            Aver.IsFalse(allMatched);
            var trgRow = trg[0];

            Aver.AreEqual(trgRow.Schema.FieldCount, 1);
            Aver.AreObjectsEqual(trgRow["Name"], "Henry");
        }
Beispiel #2
0
 /// <summary>
 /// Writes JSON data to the byte[]
 /// </summary>
 public static byte[] WriteToBuffer(object data, JSONWritingOptions options = null, Encoding encoding = null)
 {
     using (var ms = new MemoryStream())
     {
         Write(data, ms, options, encoding);
         return(ms.ToArray());
     }
 }
Beispiel #3
0
        /// <summary>
        /// Appends JSON representation of a map(IDictionary)
        /// </summary>
        public static void WriteMap(TextWriter wri, IDictionary data, int level, JSONWritingOptions options = null)
        {
            if (options == null)
            {
                options = JSONWritingOptions.Compact;
            }

            writeMap(wri, data, level, options);
        }
Beispiel #4
0
        /// <summary>
        /// Appends JSON representation of a map(IEnumerable(DictionaryEntry))
        /// </summary>
        public static void WriteMap(TextWriter wri, int level, JSONWritingOptions options, params DictionaryEntry[] data)
        {
            if (options == null)
            {
                options = JSONWritingOptions.Compact;
            }

            writeMap(wri, data, level, options);
        }
Beispiel #5
0
        /// <summary>
        /// Appends JSON representation of an IEnumerable
        /// </summary>
        public static void WriteArray(TextWriter wri, IEnumerable data, int level, JSONWritingOptions options)
        {
            if (options == null)
            {
                options = JSONWritingOptions.Compact;
            }

            writeArray(wri, data, level, options);
        }
Beispiel #6
0
        /// <summary>
        /// Appends JSON data into the instance of StringBuilder
        /// </summary>
        public static void Write(object data, TextWriter wri, JSONWritingOptions options = null)
        {
            if (options == null)
            {
                options = JSONWritingOptions.Compact;
            }

            writeAny(wri, data, 0, options);
        }
Beispiel #7
0
        /// <summary>
        /// Writes a string in JSON format (a la "JSON encode string") - using quotes and escaping charecters that need it
        /// </summary>
        /// <param name="wri">TextWriter instance to append data into</param>
        /// <param name="data">Original string to encode as JSON</param>
        /// <param name="opt">JSONWriting options instance, if omitted then JSONWritingOptions.Compact is used</param>
        public static void EncodeString(TextWriter wri, string data, JSONWritingOptions opt = null)
        {
            if (data.IsNullOrEmpty())
            {
                wri.Write("\"\"");
                return;
            }

            if (opt == null)
            {
                opt = JSONWritingOptions.Compact;
            }

            wri.Write('"');

            for (int i = 0; i < data.Length; i++)
            {
                char c = data[i];
                if (c > 127 && opt.ASCIITarget)
                {
                    wri.Write("\\u");
                    wri.Write(((int)c).ToString("x4"));
                    continue;
                }

                switch (c)
                {
                case '\\':  { wri.Write(@"\\"); break; }

                case '/':   { wri.Write(@"\/"); break; }

                case (char)CharCodes.Char0:     { wri.Write(@"\u0000"); break; }

                case (char)CharCodes.AlertBell: { wri.Write(@"\u"); ((int)c).ToString("x4"); break; }

                case (char)CharCodes.Backspace: { wri.Write(@"\b"); break; }

                case (char)CharCodes.Formfeed:  { wri.Write(@"\f"); break; }

                case (char)CharCodes.LF:        { wri.Write(@"\n"); break; }

                case (char)CharCodes.CR:        { wri.Write(@"\r"); break; }

                case (char)CharCodes.Tab:       { wri.Write(@"\t"); break; }

                case (char)CharCodes.VerticalQuote: { wri.Write(@"\u"); ((int)c).ToString("x4"); break; }

                case '"':  { wri.Write(@"\"""); break; }

                default: { wri.Write(c); break; }
                }
            }//for

            wri.Write('"');
        }
Beispiel #8
0
        private static void indent(TextWriter wri, int level, JSONWritingOptions opt)
        {
            if (opt.IndentWidth == 0)
            {
                return;
            }

            var total = level * opt.IndentWidth;

            for (var i = 0; i < total; i++)
            {
                wri.Write(' ');
            }
        }
Beispiel #9
0
        public void JSON_SerializeRowset_TypedRows()
        {
            var rowset = new Rowset(Schema.GetForTypedDoc(typeof(Person)));

            for (var i = 0; i < 10; i++)
            {
                rowset.Insert(new Person {
                    ID           = "POP{0}".Args(i),
                    FirstName    = "Oleg",
                    LastName     = "Popov-{0}".Args(i),
                    DOB          = new DateTime(1953, 12, 10),
                    YearsInSpace = 12
                });
            }

            // Serialization without schema
            var json = rowset.ToJSON(Azos.Serialization.JSON.JSONWritingOptions.PrettyPrint);

            Console.WriteLine(json);

            var rowset2 = json.JSONToDynamic();

            Aver.AreEqual("Popov-1", rowset2.Rows[1][2]);

            RowsetBase rowset3 = new Rowset(Schema.GetForTypedDoc(typeof(Person)));
            var        res     = Rowset.FromJSON <Person>(json, ref rowset3);

            Aver.AreEqual(10, res);
            Aver.AreEqual(10, rowset3.Count);
            Aver.AreObjectsEqual("Popov-1", rowset3[1][2]);

            var options = new Azos.Serialization.JSON.JSONWritingOptions
            {
                RowsetMetadata  = true,
                IndentWidth     = 2,
                ObjectLineBreak = true,
                MemberLineBreak = true,
                SpaceSymbols    = true,
                ASCIITarget     = false
            };

            rowset3.Clear();
            var json2 = rowset.ToJSON(options);
            var res2  = Rowset.FromJSON <Person>(json2, ref rowset3);

            Aver.AreEqual(10, res);
            Aver.AreEqual(10, rowset3.Count);
            Aver.AreObjectsEqual("Popov-1", rowset3[1][2]);
        }
Beispiel #10
0
        public void Table_FromJSON_ShemaOnly()
        {
            var src     = new Table(new TeztRow().Schema);
            var options = new Azos.Serialization.JSON.JSONWritingOptions
            {
                RowsetMetadata  = true,
                SpaceSymbols    = true,
                IndentWidth     = 2,
                MemberLineBreak = true,
                ObjectLineBreak = true
            };
            var json = src.ToJSON(options);

            var trg = RowsetBase.FromJSON(json, true);

            schemaAssertions(trg.Schema, src.Schema);
            Aver.AreEqual(trg.Count, 0);
        }
Beispiel #11
0
        private static void writeArray(TextWriter wri, IEnumerable data, int level, JSONWritingOptions opt)
        {
            wri.Write('[');

            var first = true;

            foreach (var elm in data)
            {
                if (!first)
                {
                    wri.Write(opt.SpaceSymbols ? ", " : ",");
                }
                writeAny(wri, elm, level + 1, opt);
                first = false;
            }

            wri.Write(']');
        }
Beispiel #12
0
        /// <summary>
        /// Writes JSON data to the string
        /// </summary>
        public static string Write(object data, JSONWritingOptions options = null, IFormatProvider formatProvider = null)
        {
            if (options == null)
            {
                options = JSONWritingOptions.Compact;
            }

            var sb = new StringBuilder(0xff);

            using (var wri = formatProvider == null ?
                             new StringWriter(sb) :
                             new StringWriter(sb, formatProvider))
            {
                writeAny(wri, data, 0, options);
            }

            return(sb.ToString());
        }
Beispiel #13
0
        /// <summary>
        /// Writes NLSMap either as a dict or as a {n:"", d: ""} pair as Options.NLSMapLanguageISO filter dictates
        /// </summary>
        public void WriteAsJSON(TextWriter wri, int nestingLevel, JSONWritingOptions options = null)
        {
            if (m_Data == null)
            {
                wri.Write("{}");
                return;
            }

            if (options == null ||
                options.Purpose == JSONSerializationPurpose.Marshalling ||
                options.NLSMapLanguageISO.IsNullOrWhiteSpace())
            {
                JSONWriter.WriteMap(wri, nestingLevel, options,
                                    m_Data.Select
                                    (
                                        e => new System.Collections.DictionaryEntry(IOUtils.UnpackISO3CodeFromInt(e.ISO), e)
                                    ).ToArray());

                return;
            }

            var pair = this[options.NLSMapLanguageISO];

            if (!pair.IsAssigned && !options.NLSMapLanguageISODefault.EqualsOrdIgnoreCase(options.NLSMapLanguageISO))
            {
                pair = this[options.NLSMapLanguageISODefault];
            }

            if (pair.IsAssigned)
            {
                JSONWriter.WriteMap(wri, nestingLevel, options, new System.Collections.DictionaryEntry("n", pair.Name),
                                    new System.Collections.DictionaryEntry("d", pair.Description));
            }
            else
            {
                JSONWriter.WriteMap(wri, nestingLevel, options, new System.Collections.DictionaryEntry("n", null),
                                    new System.Collections.DictionaryEntry("d", null));
            }
        }
Beispiel #14
0

        
Beispiel #15
0
 /// <summary>
 /// Writes JSON data to the file
 /// </summary>
 public static void WriteToFile(object data, string fileName, JSONWritingOptions options = null, Encoding encoding = null)
 {
     using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
         Write(data, fs, options, encoding);
 }
Beispiel #16
0
        private static void writeMap(TextWriter wri, IEnumerable <DictionaryEntry> data, int level, JSONWritingOptions opt)
        {
            if (level > 0)
            {
                level++;
            }

            if (opt.ObjectLineBreak)
            {
                wri.WriteLine();
                indent(wri, level, opt);
            }

            wri.Write('{');

            var first = true;

            foreach (DictionaryEntry entry in data)
            {
                //20160324 DKh
                if (opt.MapSkipNulls)
                {
                    if (entry.Value == null)
                    {
                        continue;
                    }

                    // 20161009 Dkh, Ogee NLSMap is a special type which is treated as a ref type for perf optimization
                    if (entry.Value is NLSMap && ((NLSMap)entry.Value).Count == 0)
                    {
                        continue;
                    }
                }

                if (!first)
                {
                    wri.Write(opt.SpaceSymbols ? ", " : ",");
                }

                if (opt.MemberLineBreak)
                {
                    wri.WriteLine();
                    indent(wri, level + 1, opt);
                }
                EncodeString(wri, entry.Key.ToString(), opt);
                wri.Write(opt.SpaceSymbols ? ": " : ":");
                writeAny(wri, entry.Value, level + 1, opt);
                first = false;
            }

            if (!first && opt.MemberLineBreak)
            {
                wri.WriteLine();
                indent(wri, level, opt);
            }

            wri.Write('}');
        }
Beispiel #17
0
 private static void writeMap(TextWriter wri, IDictionary data, int level, JSONWritingOptions opt)
 {
     writeMap(wri, new dictEnumberable(data), level, opt);
 }
Beispiel #18
0
 /// <summary>
 /// Writes JSON data to the stream
 /// </summary>
 public static void Write(object data, Stream stream, JSONWritingOptions options = null, Encoding encoding = null)
 {
     using (var writer = new StreamWriter(stream, encoding ?? UTF8Encoding.UTF8))
         Write(data, writer, options);
 }
Beispiel #19
0
        private static void writeAny(TextWriter wri, object data, int level, JSONWritingOptions opt)
        {
            if (data == null)
            {
                wri.Write("null");
                return;
            }

            if (level > opt.MaxNestingLevel)
            {
                throw new JSONSerializationException(StringConsts.JSON_SERIALIZATION_MAX_NESTING_EXCEEDED_ERROR.Args(opt.MaxNestingLevel));
            }

            if (data is string)
            {
                EncodeString(wri, (string)data, opt);
                return;
            }

            if (data is bool)                               //the check is here for speed
            {
                wri.Write(((bool)data) ? "true" : "false"); //do NOT LOCALIZE!
                return;
            }

            if (data is int || data is long)                //the check is here for speed
            {
                wri.Write(((IConvertible)data).ToString(System.Globalization.CultureInfo.InvariantCulture));
                //20140619 Dkh+Dlat wri.Write(data.ToString());
                return;
            }

            if (data is double || data is float || data is decimal)                //the check is here for speed
            {
                wri.Write(((IConvertible)data).ToString(System.Globalization.CultureInfo.InvariantCulture));
                //20140619 Dkh+Dlat wri.Write(data.ToString());
                return;
            }

            if (data is DateTime)
            {
                EncodeDateTime(wri, (DateTime)data, opt);
                return;
            }

            if (data is TimeSpan)                //20140619 Dlat
            {
                var ts = (TimeSpan)data;
                wri.Write(ts.Ticks);
                return;
            }

            if (data is IJSONWritable)                //these types know how to directly write themselves
            {
                ((IJSONWritable)data).WriteAsJSON(wri, level, opt);
                return;
            }

            if (data is Serialization.JSON.JSONDynamicObject)                //unwrap dynamic
            {
                writeAny(wri, ((Serialization.JSON.JSONDynamicObject)data).Data, level, opt);
                return;
            }


            if (data is IDictionary)                //must be BEFORE IEnumerable
            {
                writeMap(wri, (IDictionary)data, level, opt);
                return;
            }

            if (data is IEnumerable)
            {
                writeArray(wri, (IEnumerable)data, level, opt);
                return;
            }

            var tdata = data.GetType();

            if (tdata.IsPrimitive || tdata.IsEnum)
            {
                string val;
                if (data is IConvertible)
                {
                    val = ((IConvertible)data).ToString(System.Globalization.CultureInfo.InvariantCulture);
                }
                else
                {
                    val = data.ToString();
                }

                EncodeString(wri, val, opt);
                return;
            }

            var fields = SerializationUtils.GetSerializableFields(tdata);

            //20150620 DKh
            //var dict = new Dictionary<string, object>();
            //foreach(var f in fields)
            //{
            //    var name = f.Name;
            //    var iop = name.IndexOf('<');
            //    if (iop>=0)//handle anonymous type field name
            //    {
            //        var icl = name.IndexOf('>');
            //        if (icl>iop+1)
            //            name = name.Substring(iop+1, icl-iop-1);
            //    }
            //    dict.Add(name, f.GetValue(data));
            //}

            var dict = fields.Select(
                f =>
            {
                var name = f.Name;
                var iop  = name.IndexOf('<');
                if (iop >= 0)            //handle anonymous type field name
                {
                    var icl = name.IndexOf('>');
                    if (icl > iop + 1)
                    {
                        name = name.Substring(iop + 1, icl - iop - 1);
                    }
                }

                return(new DictionaryEntry(name, f.GetValue(data)));
            });                //select


            writeMap(wri, dict, level, opt);
        }
Beispiel #20
0
 void IJSONWritable.WriteAsJSON(TextWriter wri, int nestingLevel, JSONWritingOptions options)
 {
     JSONWriter.WriteMap(wri, nestingLevel, options, new System.Collections.DictionaryEntry("n", Name),
                         new System.Collections.DictionaryEntry("d", Description));
 }
Beispiel #21
0
        /// <summary>
        /// Writes a string in JSON format (a la "JSON encode string") - using quotes and escaping charecters that need it
        /// </summary>
        /// <param name="wri">TextWriter instance to append data into</param>
        /// <param name="data">Original string to encode as JSON</param>
        /// <param name="opt">JSONWriting options instance, if omitted then JSONWritingOptions.Compact is used</param>
        /// <param name="utcOffset">UTC offset override. If not supplied then offset form local time zone is used</param>
        public static void EncodeDateTime(TextWriter wri, DateTime data, JSONWritingOptions opt = null, TimeSpan?utcOffset = null)
        {
            if (opt == null)
            {
                opt = JSONWritingOptions.Compact;
            }

            if (!opt.ISODates)
            {
                wri.Write("new Date({0})".Args(data.ToMillisecondsSinceUnixEpochStart()));
                return;
            }

            wri.Write('"');
            var year = data.Year;

            if (year > 999)
            {
                wri.Write(year);
            }
            else if (year > 99)
            {
                wri.Write('0'); wri.Write(year);
            }
            else if (year > 9)
            {
                wri.Write("00"); wri.Write(year);
            }
            else if (year > 0)
            {
                wri.Write("000"); wri.Write(year);
            }

            wri.Write('-');

            var month = data.Month;

            if (month > 9)
            {
                wri.Write(month);
            }
            else
            {
                wri.Write('0'); wri.Write(month);
            }

            wri.Write('-');

            var day = data.Day;

            if (day > 9)
            {
                wri.Write(day);
            }
            else
            {
                wri.Write('0'); wri.Write(day);
            }

            wri.Write('T');

            var hour = data.Hour;

            if (hour > 9)
            {
                wri.Write(hour);
            }
            else
            {
                wri.Write('0'); wri.Write(hour);
            }

            wri.Write(':');

            var minute = data.Minute;

            if (minute > 9)
            {
                wri.Write(minute);
            }
            else
            {
                wri.Write('0'); wri.Write(minute);
            }

            wri.Write(':');

            var second = data.Second;

            if (second > 9)
            {
                wri.Write(second);
            }
            else
            {
                wri.Write('0'); wri.Write(second);
            }

            var ms = data.Millisecond;

            if (ms > 0)
            {
                wri.Write('.');

                if (ms > 99)
                {
                    wri.Write(ms);
                }
                else if (ms > 9)
                {
                    wri.Write('0'); wri.Write(ms);
                }
                else
                {
                    wri.Write("00"); wri.Write(ms);
                }
            }

            if (data.Kind == DateTimeKind.Utc)
            {
                wri.Write('Z');
            }
            else
            {
                //var offset = utcOffset==null ? TimeZoneInfo.Local.BaseUtcOffset : utcOffset.Value;
                //dlat 2014/06/15
                var offset = utcOffset == null?TimeZoneInfo.Local.GetUtcOffset(data) : utcOffset.Value;

                wri.Write(offset.Ticks < 0 ? '-' : '+');

                hour = Math.Abs(offset.Hours);
                if (hour > 9)
                {
                    wri.Write(hour);
                }
                else
                {
                    wri.Write('0'); wri.Write(hour);
                }

                wri.Write(':');

                minute = Math.Abs(offset.Minutes);
                if (minute > 9)
                {
                    wri.Write(minute);
                }
                else
                {
                    wri.Write('0'); wri.Write(minute);
                }
            }


            wri.Write('"');
        }
Beispiel #22
0
        public void Rowset_FromJSON(bool rowsAsMap)
        {
            var row = new TeztRow();
            var src = new Rowset(row.Schema);

            row.BoolField     = true;
            row.CharField     = 'a';
            row.StringField   = "aaa";
            row.DateTimeField = new DateTime(2016, 1, 2);
            row.GDIDField     = new GDID(1, 2, 3);

            row.ByteField  = 100;
            row.ShortField = -100;
            row.IntField   = -999;

            row.UIntField = 254869;
            row.LongField = -267392;

            row.FloatField  = 32768.32768F;
            row.DoubleField = -1048576.1048576D;

            row.DecimalField = 1.0529M;

            row.NullableField = null;

            row.ArrayInt   = new int[] { -1, 0, 1 };
            row.ListString = new List <string> {
                "one", "two", "three"
            };
            row.DictionaryIntStr = new Dictionary <int, string>
            {
                { 1, "first" },
                { 2, "second" }
            };

            row.RowField = new Person {
                Name = "John", Age = 20
            };

            src.Add(row);

            row.BoolField     = false;
            row.CharField     = 'b';
            row.StringField   = "bbb";
            row.DateTimeField = new DateTime(2016, 2, 1);
            row.GDIDField     = new GDID(4, 5, 6);

            row.ByteField  = 101;
            row.ShortField = 100;
            row.IntField   = 999;

            row.UIntField = 109876;
            row.LongField = 267392;

            row.FloatField  = -32768.32768F;
            row.DoubleField = -048576.1048576D;

            row.DecimalField = -1.0529M;

            row.NullableField = null;

            row.ArrayInt   = new int[] { 1, 0, -1 };
            row.ListString = new List <string> {
                "three", "two", "one"
            };
            row.DictionaryIntStr = new Dictionary <int, string>
            {
                { 0, "zero" },
                { 1, "first" },
                { 2, "second" }
            };

            row.RowField = new Person {
                Name = "Ann", Age = 19
            };

            src.Add(row);

            var options = new Azos.Serialization.JSON.JSONWritingOptions
            {
                RowsetMetadata  = true,
                SpaceSymbols    = true,
                IndentWidth     = 2,
                MemberLineBreak = true,
                ObjectLineBreak = true,
                RowsAsMap       = rowsAsMap
            };
            var json = src.ToJSON(options);

            var trg = RowsetBase.FromJSON(json);

            schemaAssertions(trg.Schema, src.Schema);
            rowsAssertions(src, trg, rowsAsMap);
        }