Beispiel #1
0
        public void Values_bool_should_be_an_bool()
        {
            var obj = new BoolPoco
            {
                Val = true,
                Id  = 4
            };
            var json = JsonSerializer.ToJson(obj);

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("{\"Val\":true,\"Id\":4}", json);
            var newobj = JsonSerializer.ToObject <BoolPoco>(json);

            Assert.IsTrue(newobj.Val);

            obj = new BoolPoco
            {
                Val = false,
                Id  = 5
            };
            json = JsonSerializer.ToJson(obj);
            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("{\"Val\":false,\"Id\":5}", json);
            newobj = JsonSerializer.ToObject <BoolPoco>(json);
            Assert.IsTrue(newobj.Val == false);
        }
Beispiel #2
0
        public void Json_text_with_different_encoding_should_be_interoperated()
        {
            var json = JsonSerializer.ToJson(new { Email = "*****@*****.**", Name = "san" });

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("{\"Email\":\"[email protected]\",\"Name\":\"san\"}", json);

            //encoding without bom
            var utf32      = new UTF32Encoding(false, false);
            var utf16      = new UnicodeEncoding(false, false);
            var utf8       = new UTF8Encoding(false);
            var utf32Bytes = utf32.GetBytes(json);
            var utf16Bytes = utf16.GetBytes(json);

            //Direct reading of other byte streams, failed
            var utf32String = utf8.GetString(utf32Bytes);
            var utf16String = utf8.GetString(utf16Bytes);

            Assert.AreNotEqual(utf32String, json);
            Assert.AreNotEqual(utf16String, json);

            //Convert byte stream, successful
            var utf8Bytes = Encoding.Convert(utf16, utf8, utf16Bytes);

            utf16String = utf8.GetString(utf8Bytes);
            Assert.AreEqual(json, utf16String);

            utf8Bytes   = Encoding.Convert(utf32, utf8, utf32Bytes);
            utf32String = utf8.GetString(utf8Bytes);
            Assert.AreEqual(json, utf32String);
        }
        public void Linq_serialize_should_be_correct_format()
        {
            var json = JsonSerializer.ToJson(Enumerable.Range(0, 5000).Select(i => i * 1.1m));

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.IsNotNull(json);
        }
Beispiel #4
0
        public void Values_number_should_be_an_number()
        {
            var i    = 15;
            var json = JsonSerializer.ToJson(new { val = i });

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("{\"val\":15}", json);
            object newobj = JsonSerializer.ToObject <object>(json);

            Assert.IsTrue(IsNumeric(((JObject)newobj)["val"].ToString()));

            var f = 22.113f;

            json = JsonSerializer.ToJson(new { val = f });
            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("{\"val\":22.113}", json);
            newobj = JsonSerializer.ToObject <object>(json);
            Assert.IsTrue(IsNumeric(((JObject)newobj)["val"].ToString()));

            var m = 10.01m;

            json = JsonSerializer.ToJson(new { val = m });
            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("{\"val\":10.01}", json);
            newobj = JsonSerializer.ToObject <object>(json);
            Assert.IsTrue(IsNumeric(((JObject)newobj)["val"].ToString()));

            var e = 2.01e2;

            json = JsonSerializer.ToJson(new { val = e });
            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("{\"val\":201}", json);
            newobj = JsonSerializer.ToObject <object>(json);
            Assert.IsTrue(IsNumeric(((JObject)newobj)["val"].ToString()));
        }
        public void DataTable_with_nullvalue_serialize_should_be_correct_format()
        {
            DataTable   dt    = new DataTable();
            List <Type> types = new List <Type>
            {
                typeof(TimeSpan),
                typeof(char[]),
                typeof(Type),
                typeof(object),
                typeof(byte[]),
                typeof(Uri),
                typeof(Guid)
            };

            foreach (var ss in types)
            {
                dt.Columns.Add(ss.Name, ss);
            }

            dt.Rows.Add(types.Select(t => (object)null).ToArray());

            var json = JsonSerializer.ToJson(dt);

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("[{\"TimeSpan\":null,\"Char[]\":null,\"Type\":null,\"Object\":null,\"Byte[]\":null,\"Uri\":null,\"Guid\":null}]", json);
        }
        public void Exception_serialize_should_be_correct_format()
        {
            Exception e = null;

            try
            {
                var x = int.Parse("330") / int.Parse("0");
            }
            catch (Exception _) { e = _; }

            Assert.IsNotNull(e);

            var obj =
                new IssueException
            {
                DateField = DateTime.UtcNow,
                IntField  = 123,
                DictField = new Dictionary <string, object> {
                    { "foo", "bar" }
                },
                ExceptionField = e
            };

            var str = JsonSerializer.ToJson(obj);

            Assert.IsTrue(JsonValidator.IsValid(str));
            Assert.IsNotNull(str);
        }
        public void Text_should_be_correct_format()
        {
            //JSON-text = ws value ws
            var json = JsonSerializer.ToJson("normal text");

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("\"normal text\"", json);

            //%x20              ; Space
            json = JsonSerializer.ToJson("normal text\u0020");
            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("\"normal text \"", json);

            //%x09              ; Horizontal tab
            json = JsonSerializer.ToJson("normal text\u0009");
            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("\"normal text\\t\"", json);

            //%x0A              ; Line feed or New line
            json = JsonSerializer.ToJson("normal text\u000a");
            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("\"normal text\\n\"", json);

            //%x0D              ; Carriage return
            json = JsonSerializer.ToJson("\u000dnormal text");
            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("\"\\rnormal text\"", json);
        }
Beispiel #8
0
        public void Json_text_with_unicode_entirely_should_be_parse_interoperable_in_all_implementations()
        {
            var objs = new List <SimplePoco>
            {
                new SimplePoco {
                    Name = "\u0098\u0099", Id = 3
                },
                new SimplePoco {
                    Name = "\u1f33\u1f32", Id = 2
                },
                new SimplePoco {
                    Name = "\u5fee\u5fef", Id = 1
                }
            };
            var json = JsonSerializer.ToJson(objs);

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("[{\"Name\":\"\u0098\u0099\",\"Id\":3},{\"Name\":\"ἳἲ\",\"Id\":2},{\"Name\":\"忮忯\",\"Id\":1}]", json);

            var newobjs = JsonSerializer.ToObject <List <SimplePoco> >(json);

            Assert.IsTrue(objs[0].Name == newobjs[0].Name);
            Assert.IsTrue(objs[1].Name == newobjs[1].Name);
            Assert.IsTrue(objs[2].Name == newobjs[2].Name);
        }
        public void Json_serialize_should_be_consider_security()
        {
            //Security Considerations
            //front-end interactive: system variable needs avoid(eg, window)
            var obj = new Root {
                window = new Window {
                    onclick = "alert(123)"
                }
            };
            var json = JsonSerializer.ToJson(obj);

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("{\"window\":{\"onclick\":\"alert(123)\"}}", json);
            var json1 = json;

            Assert.ThrowsException <AssertFailedException>(() =>
            {
                StringAssert.DoesNotMatch(json1, new Regex("\"window\":"));
            });
            //directly generates executable code
            var str = "alert('hello world')";

            json = JsonSerializer.ToJson(str);
            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("\"alert('hello world')\"", json);
            Assert.ThrowsException <AssertFailedException>(() =>
            {
                StringAssert.DoesNotMatch(json, new Regex("alert[(](.*?)[)]"));
            });
        }
        public void Object_should_be_correct_format()
        {
            var data = new SimplePoco
            {
                Name = "abc",
                Id   = 999
            };
            var json = JsonSerializer.ToJson(data);

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("{\"Name\":\"abc\",\"Id\":999}", json);

            //begin-object    = ws %x7B ws; { left curly bracket
            Assert.IsTrue(json.StartsWith("{"));

            //end-array       = ws %x7D ws;} right curly bracket
            Assert.IsTrue(json.EndsWith("}"));

            //name-separator  = ws %x3A ws; : colon
            //value - separator = ws % x2C ws; , comma
            var splitarray = json.Split('\"');

            Assert.AreEqual(":", splitarray[2]);
            Assert.AreEqual(",", splitarray[4]);
        }
        public void DataTable_with_value_serialize_should_be_correct_format()
        {
            DataTable dt = new DataTable();
            Dictionary <Type, object> types = new Dictionary <Type, object>
            {
                [typeof(TimeSpan)] = TimeSpan.Zero,
                [typeof(char[])]   = new char[] { 'a', 'b', 'c' },
                [typeof(Type)]     = typeof(string),
                [typeof(object)]   = new object(),
                [typeof(byte[])]   = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 },
                [typeof(Uri)]      = new Uri("http://localhost"),
                [typeof(Guid)]     = new Guid(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
            };

            foreach (var ss in types)
            {
                dt.Columns.Add(ss.Key.Name, ss.Key);
            }

            dt.Rows.Add(types.Select(t => t.Value).ToArray());

            var json = JsonSerializer.ToJson(dt, new JsonSerializerOption()
            {
                TimespanFormat = TimespanFormatEnum.Microsoft
            });

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("[{\"TimeSpan\":\"00:00:00\",\"Char[]\":[\"a\",\"b\",\"c\"],\"Type\":\"System.String, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e\",\"Object\":{},\"Byte[]\":[1,2,3,4,5,6,7,8],\"Uri\":\"http://localhost\",\"Guid\":\"00000001-0002-0003-0405-060708090a0b\"}]", json);
        }
Beispiel #12
0
        public void ComplexKeyValuePair_deserialize_should_be_correct()
        {
            DateTime dateTime = new DateTime(2000, 12, 1, 23, 1, 1, DateTimeKind.Utc);

            List <KeyValuePair <string, WagePerson> > list = new List <KeyValuePair <string, WagePerson> >();

            list.Add(new KeyValuePair <string, WagePerson>("key1", new WagePerson
            {
                BirthDate    = dateTime,
                Department   = "Department1",
                LastModified = dateTime,
                HourlyWage   = 1
            }));
            list.Add(new KeyValuePair <string, WagePerson>("key2", new WagePerson
            {
                BirthDate    = dateTime,
                Department   = "Department2",
                LastModified = dateTime,
                HourlyWage   = 2
            }));

            string json = JsonSerializer.ToJson(list);

            Assert.IsTrue(JsonValidator.IsValid(json));

            List <KeyValuePair <string, WagePerson> > result = JsonSerializer.ToObject <List <KeyValuePair <string, WagePerson> > >(json);

            Assert.AreEqual(2, result.Count);
            Assert.AreEqual("key1", result[0].Key);
            Assert.AreEqual(1, result[0].Value.HourlyWage);
            Assert.AreEqual("key2", result[1].Key);
            Assert.AreEqual(2, result[1].Value.HourlyWage);
        }
Beispiel #13
0
        public void KeyValuePair_deserialize_should_be_correct()
        {
            List <KeyValuePair <string, string> > list = new List <KeyValuePair <string, string> >();

            list.Add(new KeyValuePair <string, string>("key1", "value1"));
            list.Add(new KeyValuePair <string, string>("key2", "value2"));

            string json = JsonSerializer.ToJson(list);

            Assert.IsTrue(JsonValidator.IsValid(json));

            List <KeyValuePair <string, string> > result = JsonSerializer.ToObject <List <KeyValuePair <string, string> > >(json);

            Assert.AreEqual(2, result.Count);
            Assert.AreEqual("key1", result[0].Key);
            Assert.AreEqual("value1", result[0].Value);
            Assert.AreEqual("key2", result[1].Key);
            Assert.AreEqual("value2", result[1].Value);

            IList <KeyValuePair <string, string> > values = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("123", "2017-05-19T11:00:59")
            };

            json = JsonSerializer.ToJson(values);
            Assert.IsTrue(JsonValidator.IsValid(json));

            IList <KeyValuePair <string, string> > v1 = JsonSerializer.ToObject <IList <KeyValuePair <string, string> > >(json);

            Assert.AreEqual("123", v1[0].Key);
            Assert.AreEqual("2017-05-19T11:00:59", v1[0].Value);
        }
        public void IgnoreDefaultValueFeature_use_attribute_should_be_work_correct()
        {
            var json = JsonSerializer.ToJson(new User2());

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("{\"Age\":0,\"Name\":null}", json);
        }
        public void IgnoreDefaultValueFeature_use_classAttribute_should_be_work_correct()
        {
            var json = JsonSerializer.ToJson(new User());

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("{}", json);
        }
        public void UIntPtr_should_be_serialize_correct()
        {
            UIntPtr p    = new UIntPtr(0xC01E0001);
            var     json = JsonSerializer.ToJson(p);

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual(p.ToString(), json);
        }
        public void Unassigned_array_should_be_serialize_to_correct_format()
        {
            var x    = new int[2];
            var json = Json.JsonSerializer.ToJson(x);

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("[0,0]", json);
        }
Beispiel #18
0
        public void Unassigned_object_should_be_serialize_to_correct_format()
        {
            var data = new SimplePoco();
            var json = JsonSerializer.ToJson(data);

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("{\"Name\":null,\"Id\":0}", json);
        }
Beispiel #19
0
        public void DBNullValue_serialize_should_be_an_null()
        {
            var value = DBNull.Value;
            var json  = JsonSerializer.ToJson(value);

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("null", json);
        }
Beispiel #20
0
        public void AnonymousType_should_be_serialize_to_correct_format()
        {
            var json = JsonSerializer.ToJson(
                new { Hoge = 100, Huga = true, Yaki = new { Rec = 1, T = 10 }, Nano = "nanoanno" });

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual(@"{""Hoge"":100,""Huga"":true,""Yaki"":{""Rec"":1,""T"":10},""Nano"":""nanoanno""}", json);
        }
Beispiel #21
0
        public void Empty_object_should_be_serialize_to_correct_format()
        {
            var data = new {};
            var json = JsonSerializer.ToJson(data);

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("{}", json);
        }
        public void IntPtr_should_be_serialize_correct()
        {
            var    str  = "abc";
            IntPtr p    = Marshal.StringToHGlobalAnsi(str);
            var    json = JsonSerializer.ToJson(p);

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual(((long)p).ToString(), json);
        }
Beispiel #23
0
        public override string Format(string input)
        {
            if (!_validator.IsValid(input))
            {
                throw new ValidationException();
            }

            return("formatlanmış metin");
        }
Beispiel #24
0
        public void Json_text_escaped_unicode_and_origin_compare_should_be_equal()
        {
            var json1 = JsonSerializer.ToJson(new { Email = "a\\b" });
            var json2 = JsonSerializer.ToJson(new { Email = "a\u005Cb" });

            Assert.IsTrue(JsonValidator.IsValid(json1));
            Assert.IsTrue(JsonValidator.IsValid(json2));
            Assert.AreEqual(json1, json2);
        }
        public void ArraySegment_deserialize_should_be_correct()
        {
            ArraySegment <int> ast = new ArraySegment <int>(new int[] { 1 });
            var json = JsonSerializer.ToJson(ast);
            var obj  = JsonSerializer.ToObject <ArraySegment <int> >(json);

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual(1, obj.First());
        }
Beispiel #26
0
        public void LazyObject_should_be_serialize_to_correct_format()
        {
            Lazy <Student> stu = new Lazy <Student>();

            stu.Value.Name = "Tom";
            stu.Value.Age  = 21;
            var json = JsonSerializer.ToJson(stu);

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("{\"Name\":\"Tom\",\"Age\":21}", json);
        }
        public void SortedSet_deserialize_should_be_correct()
        {
            SortedSet <int> sortedSet = new SortedSet <int>();

            sortedSet.Add(1);
            var json = JsonSerializer.ToJson(sortedSet);
            var obj  = JsonSerializer.ToObject <SortedSet <int> >(json);

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual(1, obj.First());
        }
        public void HashSet_deserialize_should_be_correct()
        {
            HashSet <int> hashset = new HashSet <int>();

            hashset.Add(1);
            var json = JsonSerializer.ToJson(hashset);
            var obj  = JsonSerializer.ToObject <HashSet <int> >(json);

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual(1, obj.First());
        }
        public void ConcurrentDictionary_deserialize_should_be_correct()
        {
            ConcurrentDictionary <string, string> cDic = new ConcurrentDictionary <string, string>();

            cDic.TryAdd("1", "1");
            var json = JsonSerializer.ToJson(cDic);
            var obj  = JsonSerializer.ToObject <ConcurrentDictionary <string, string> >(json);

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("1", obj["1"]);
        }
        public void SortedDictionary_deserialize_should_be_correct()
        {
            SortedDictionary <string, string> sortDic = new SortedDictionary <string, string> {
                { "1", "1" }
            };
            var json = JsonSerializer.ToJson(sortDic);
            var obj  = JsonSerializer.ToObject <SortedDictionary <string, string> >(json);

            Assert.IsTrue(JsonValidator.IsValid(json));
            Assert.AreEqual("1", obj["1"]);
        }