예제 #1
0
        public string serializeToJsonString()
        {
            Dictionary <string, object> data           = getData();
            IJsonSerializer             JsonSerializer = new DefaultJsonSerializer();

            return(JsonSerializer.Serialize(data));
        }
예제 #2
0
        public void ReferenceLoopHandling_Test_Should_Succeed()
        {
            var options = A.Fake <IOptions <EasyCachingJsonSerializerOptions> >();

            A.CallTo(() => options.Value).Returns(new EasyCachingJsonSerializerOptions()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            });

            var serializer = new DefaultJsonSerializer(options);

            Employee joe = new Employee {
                Name = "Joe User"
            };
            Employee mike = new Employee {
                Name = "Mike Manager"
            };

            joe.Manager  = mike;
            mike.Manager = mike;

            var joe_byte = serializer.Serialize(joe);
            var joe_obj  = serializer.Deserialize <Employee>(joe_byte);


            Assert.Equal(joe.Name, joe_obj.Name);
            Assert.Equal(joe.Manager, mike);
        }
예제 #3
0
        public void Should_use_wcf_datetimeformat_when_iso8601dateformat_local_override_is_false()
        {
            // Given
            var environment = GetTestableEnvironment(x => x.Json());
            var sut         = new DefaultJsonSerializer(environment)
            {
                ISO8601DateFormat = false
            };
            var input = new
            {
                UnspecifiedDateTime = new DateTime(2014, 3, 9, 17, 03, 25).AddMilliseconds(234),
                LocalDateTime       = new DateTime(2014, 3, 9, 17, 03, 25, DateTimeKind.Local).AddMilliseconds(234),
                UtcDateTime         = new DateTime(2014, 3, 9, 16, 03, 25, DateTimeKind.Utc).AddMilliseconds(234)
            };

            // When
            var output = new MemoryStream();

            sut.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            var ticks = (input.LocalDateTime.ToUniversalTime().Ticks - InitialJavaScriptDateTicks) / (long)10000;

            actual.ShouldEqual(string.Format(@"{{""unspecifiedDateTime"":""\/Date({0}{1})\/"",""localDateTime"":""\/Date({0}{1})\/"",""utcDateTime"":""\/Date(1394381005234)\/""}}",
                                             ticks, GetTimezoneSuffix(input.LocalDateTime)));
        }
예제 #4
0
        public void Should_Decode_Token_To_Json_Encoded_String()
        {
            var jsonSerializer = new DefaultJsonSerializer();
            var expectedPayload = jsonSerializer.Serialize(customer);

            string decodedPayload = JsonWebToken.Decode(token, "ABC", false);

            Assert.Equal(expectedPayload, decodedPayload);
        }
        public void Should_Save_Serializer_If_Type_Not_Allready_In_Cache()
        {
            /* Setup */
            var obj = new SerializerTestClass {
                StringProp = Guid.NewGuid().ToString()
            };

            _cachedSerializers
            .Setup(c => c.Add(
                       It.Is <Type>(type => type == typeof(SerializerTestClass)),
                       It.IsAny <DataContractJsonSerializer>()))
            .Verifiable();

            /* Test */
            _serializer.Serialize(obj);

            /* Assert */
            _cachedSerializers.VerifyAll();
        }
        public void Serialize_ReturnsCorrectJson <T>(string dateFormat, NamingStrategy enumNamingStrategy, T item, string expected)
        {
            var serializer = new DefaultJsonSerializer(enumNamingStrategy)
            {
                DateFormat = dateFormat
            };

            var actual = serializer.Serialize(item);

            AssertExtension.AreObjectsValuesEqual(expected, actual);
        }
        private void datetimeTest()
        {
            ISerializer Ser = new DefaultJsonSerializer();
            string      str;

            //默认时间格式测试
            str = Ser.Serialize(new SerObj());
            //Assert.AreEqual("{\"Time\":\"2000-10-10T12:00:00\"}",str);
            StringAssert.Contains(str, "{\"Time\":\"2000-10-10T17:00:00\"}");
            if (Ser is DefaultJsonSerializer js)
            {
                //微软日期格式测试
                js.Config.Settings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
                str = Ser.Serialize(new SerObj());
                StringAssert.Contains(str, "{\"Time\":\"\\/Date(971168400000+0800)\\/\"}");
                //自定义日期时间格式测试
                js.Config.Settings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                str = Ser.Serialize(new SerObj());
                StringAssert.Contains(str, "{\"Time\":\"2000-10-10 17:00:00\"}");
            }
        }
        public void CanRoundtripToJson()
        {
            var serializer = new DefaultJsonSerializer();
            var originalData = new Data { Message = "test", Number = 42, Assertion = true };

            string serializedData = serializer.Serialize(originalData);
            var deserializedData = serializer.Deserialize<Data>(serializedData);

            Assert.That(deserializedData.Message, Is.EqualTo(originalData.Message));
            Assert.That(deserializedData.Number, Is.EqualTo(originalData.Number));
            Assert.That(deserializedData.Assertion, Is.EqualTo(originalData.Assertion));
        }
예제 #9
0
        /// <summary>
        /// 将对象序列化成缩进结构的JSON,便于日志记录
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToDumpJson(this object obj)
        {
            if (obj == null)
            {
                return("null");
            }

            DefaultJsonSerializer  serializer = ObjectFactory.New <DefaultJsonSerializer>();
            JsonSerializerSettings settings   = serializer.GetJsonSerializerSettings(true);

            // 设置为缩进格式
            settings.Formatting = Formatting.Indented;
            return(serializer.Serialize(obj, settings));
        }
예제 #10
0
        public void Should_camel_case_field_names_by_default()
        {
            // Given
            var input = new PersonWithFields { FirstName = "Joe", LastName = "Doe" };
            var serializer = new DefaultJsonSerializer(GetTestableEnvironment());

            // When
            var output = new MemoryStream();
            serializer.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            actual.ShouldEqual("{\"firstName\":\"Joe\",\"lastName\":\"Doe\"}");
        }
예제 #11
0
        public void Should_camel_case_property_names_by_default()
        {
            // Given
            var sut = new DefaultJsonSerializer();
            var input = new { FirstName = "Joe", lastName = "Doe" };

            // When
            var output = new MemoryStream();
            sut.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            actual.ShouldEqual("{\"firstName\":\"Joe\",\"lastName\":\"Doe\"}");
        }
예제 #12
0
        public void Should_camel_case_property_names_by_default()
        {
            // Given
            var input      = new { FirstName = "Joe", lastName = "Doe" };
            var serializer = new DefaultJsonSerializer(GetTestableEnvironment());

            // When
            var output = new MemoryStream();

            serializer.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            actual.ShouldEqual("{\"firstName\":\"Joe\",\"lastName\":\"Doe\"}");
        }
예제 #13
0
        public void Should_not_change_casing_when_retain_casing_is_true()
        {
            // Given
            var input = new {FirstName = "Joe", lastName = "Doe"};
            var environment = GetTestableEnvironment(x => x.Json(retainCasing: true));
            var serializer = new DefaultJsonSerializer(environment);

            // When
            var output = new MemoryStream();
            serializer.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            actual.ShouldEqual("{\"FirstName\":\"Joe\",\"lastName\":\"Doe\"}");
        }
예제 #14
0
        public void NullValueHandling_Test_Should_Succeed()
        {
            var serializer = new DefaultJsonSerializer("json", new JsonSerializerOptions
            {
                IgnoreNullValues = true
            });

            Employee joe = new Employee {
                Name = "Joe User"
            };

            var joe_byte = serializer.Serialize(joe);
            var joe_obj  = serializer.Deserialize <Employee>(joe_byte);

            Assert.Null(joe.Manager);
        }
예제 #15
0
        public void Should_not_change_casing_when_retain_casing_is_true()
        {
            // Given
            var input       = new { FirstName = "Joe", lastName = "Doe" };
            var environment = GetTestableEnvironment(x => x.Json(retainCasing: true));
            var serializer  = new DefaultJsonSerializer(environment);

            // When
            var output = new MemoryStream();

            serializer.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            actual.ShouldEqual("{\"FirstName\":\"Joe\",\"lastName\":\"Doe\"}");
        }
예제 #16
0
        public void Should_camel_case_dictionary_keys_by_default()
        {
            // Given
            var input = new Dictionary<string, object>
            {
                { "Joe", new PersonWithFields { FirstName = "Joe" } },
                { "John", new PersonWithFields { FirstName = "John" } }
            };

            var serializer = new DefaultJsonSerializer(GetTestableEnvironment());

            // When
            var output = new MemoryStream();
            serializer.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            actual.ShouldEqual("{\"joe\":{\"firstName\":\"Joe\",\"lastName\":null},\"john\":{\"firstName\":\"John\",\"lastName\":null}}");
        }
예제 #17
0
        public void NullValueHandling_Test_Should_Succeed()
        {
            var options = A.Fake <IOptions <EasyCachingJsonSerializerOptions> >();

            A.CallTo(() => options.Value).Returns(new EasyCachingJsonSerializerOptions()
            {
                NullValueHandling = NullValueHandling.Ignore
            });

            var serializer = new DefaultJsonSerializer(options);

            Employee joe = new Employee {
                Name = "Joe User"
            };

            var joe_byte = serializer.Serialize(joe);
            var joe_obj  = serializer.Deserialize <Employee>(joe_byte);

            Assert.Null(joe.Manager);
        }
예제 #18
0
        public void Should_camel_case_property_names_if_local_override_is_set()
        {
            // Given
            var environment = GetTestableEnvironment(x => x.Json(retainCasing: true));
            var serializer  = new DefaultJsonSerializer(environment)
            {
                RetainCasing = false
            };

            var input = new { FirstName = "Joe", lastName = "Doe" };

            // When
            var output = new MemoryStream();

            serializer.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            actual.ShouldEqual("{\"firstName\":\"Joe\",\"lastName\":\"Doe\"}");
        }
예제 #19
0
        public void Should_use_iso8601_datetimes_by_default()
        {
            // Given
            var serializer = new DefaultJsonSerializer(GetTestableEnvironment());
            var input      = new
            {
                UnspecifiedDateTime = new DateTime(2014, 3, 9, 17, 03, 25).AddMilliseconds(234),
                LocalDateTime       = new DateTime(2014, 3, 9, 17, 03, 25, DateTimeKind.Local).AddMilliseconds(234),
                UtcDateTime         = new DateTime(2014, 3, 9, 16, 03, 25, DateTimeKind.Utc).AddMilliseconds(234)
            };

            // When
            var output = new MemoryStream();

            serializer.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            actual.ShouldEqual(string.Format(@"{{""unspecifiedDateTime"":""2014-03-09T17:03:25.2340000{0}"",""localDateTime"":""2014-03-09T17:03:25.2340000{0}"",""utcDateTime"":""2014-03-09T16:03:25.2340000Z""}}",
                                             GetTimezoneSuffix(input.LocalDateTime, ":")));
        }
예제 #20
0
        public void Should_not_change_casing_when_retain_casing_is_true()
        {
            JsonSettings.RetainCasing = true;
            try
            {
                // Given
                var sut = new DefaultJsonSerializer();
                var input = new {FirstName = "Joe", lastName = "Doe"};

                // When
                var output = new MemoryStream();
                sut.Serialize("application/json", input, output);
                var actual = Encoding.UTF8.GetString(output.ToArray());

                // Then
                actual.ShouldEqual("{\"FirstName\":\"Joe\",\"lastName\":\"Doe\"}");
            }
            finally
            {
                JsonSettings.RetainCasing = false;
            }
        }
예제 #21
0
        public void DefaultJsonSerializer_Test()
        {
            var o1 = new TestSerializeClass()
            {
                Id   = 1,
                Name = "zhang",
                Age  = 19
            };
            IJsonSerializer jsonSerializer = new DefaultJsonSerializer();
            var             json1          = jsonSerializer.Serialize(o1);

            var o2 = jsonSerializer.Deserialize <TestSerializeClass>(json1);

            Assert.Equal(o1.Id, o2.Id);
            Assert.Equal(o1.Name, o2.Name);
            Assert.Equal(o1.Age, o2.Age);

            var o3 = (TestSerializeClass)jsonSerializer.Deserialize(json1, typeof(TestSerializeClass));

            Assert.Equal(o1.Id, o3.Id);
            Assert.Equal(o1.Name, o3.Name);
            Assert.Equal(o1.Age, o3.Age);
        }
예제 #22
0
        public void DateOnly_Iss338_Test_Should_Succeed()
        {
            var serializer = new DefaultJsonSerializer("json", new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore,
                Converters        = new List <JsonConverter>()
                {
                    new DateOnlyJsonConverter()
                }
            });

            var dateTime = DateTime.Parse("2021-12-21 12:12:12");
            var date     = DateOnly.FromDateTime(dateTime);

            DateOnlyModel m = new DateOnlyModel {
                Name = "Joe User", Date = date
            };

            var @byte = serializer.Serialize(m);
            var @obj  = serializer.Deserialize <DateOnlyModel>(@byte);

            Assert.Equal(date, obj.Date);
        }
예제 #23
0
        public void ReferenceLoopHandling_Test_Should_Succeed()
        {
            var serializer = new DefaultJsonSerializer("json", new JsonSerializerOptions()
            {
                ReferenceHandler = ReferenceHandler.Preserve
            });

            Employee joe = new Employee {
                Name = "Joe User"
            };
            Employee mike = new Employee {
                Name = "Mike Manager"
            };

            joe.Manager  = mike;
            mike.Manager = mike;

            var joe_byte = serializer.Serialize(joe);
            var joe_obj  = serializer.Deserialize <Employee>(joe_byte);


            Assert.Equal(joe.Name, joe_obj.Name);
            Assert.Equal(joe.Manager, mike);
        }
        public HttpResponseMessage GetData(string prefered = "")
        {
            var todo = new Todo
            {
                Description = "Respond with a specific content type",
                IsCompleted = true
            };


            var content     = string.Empty;
            var contentType = string.Empty;

            if (string.Equals(prefered, "json", StringComparison.InvariantCultureIgnoreCase))
            {
                content     = _jsonSerializer.Serialize(todo);
                contentType = ContentTypes.ApplicationJson;
            }
            if (string.Equals(prefered, "xml", StringComparison.InvariantCultureIgnoreCase))
            {
                content     = _xmlSerializer.Serialize(todo);
                contentType = ContentTypes.ApplicationXml;
            }


            if (string.IsNullOrWhiteSpace(content))
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Expect a 'prefered' query parameter with value 'json' or 'xml' in request."));
            }

            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(content, Encoding.UTF8, contentType)
            };

            return(response);
        }
예제 #25
0
        public void Should_camel_case_property_names_if_local_override_is_set()
        {
            JsonSettings.RetainCasing = true;
            try
            {
                // Given
                var sut = new DefaultJsonSerializer {
                    RetainCasing = false
                };
                var input = new { FirstName = "Joe", lastName = "Doe" };

                // When
                var output = new MemoryStream();
                sut.Serialize("application/json", input, output);
                var actual = Encoding.UTF8.GetString(output.ToArray());

                // Then
                actual.ShouldEqual("{\"firstName\":\"Joe\",\"lastName\":\"Doe\"}");
            }
            finally
            {
                JsonSettings.RetainCasing = false;
            }
        }
예제 #26
0
        public void Should_camel_case_dictionary_keys_by_default()
        {
            // Given
            var input = new Dictionary <string, object>
            {
                { "Joe", new PersonWithFields {
                      FirstName = "Joe"
                  } },
                { "John", new PersonWithFields {
                      FirstName = "John"
                  } }
            };

            var serializer = new DefaultJsonSerializer(GetTestableEnvironment());

            // When
            var output = new MemoryStream();

            serializer.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            actual.ShouldEqual("{\"joe\":{\"firstName\":\"Joe\",\"lastName\":null},\"john\":{\"firstName\":\"John\",\"lastName\":null}}");
        }
예제 #27
0
        public async Task <bool> Handle(Subscribe2Command message, CancellationToken ct)
        {
            var response = await _httpClientFactory.CreateClient("Subscriptions.API").PutAsync("subscribe2",
                                                                                               new StringContent(_jsonSerializer.Serialize(new SubscribeDTO($"Discord:{message.ChannelId}", message.NexusModsUrl)), Encoding.UTF8, "application/json"),
                                                                                               ct);

            return(response.IsSuccessStatusCode);
        }
예제 #28
0
        public void Should_camel_case_property_names_if_local_override_is_set()
        {
            // Given
            var environment = GetTestableEnvironment(x => x.Json(retainCasing: true));
            var serializer = new DefaultJsonSerializer(environment) { RetainCasing = false };

            var input = new { FirstName = "Joe", lastName = "Doe" };

            // When
            var output = new MemoryStream();
            serializer.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            actual.ShouldEqual("{\"firstName\":\"Joe\",\"lastName\":\"Doe\"}");
        }
예제 #29
0
 public void SerializeCypherRequest__IsValid()
 {
     var request =
         CypherQueryRequest.Create(
                                   @"START x=node(1), y=node(2) CREATE x-[r:OWNS {""name"":""mark""}]->y<-[r2:IS_OWNED_BY {""age"": 33}]");
     var serializer = new DefaultJsonSerializer();
     var result = serializer.Serialize(request);
     Console.WriteLine(result);
 }
예제 #30
0
        /// <summary>
        /// 将一个对象序列化为JSON字符串。
        /// </summary>
        /// <param name="obj">要序列化的对象</param>
        /// <returns>序列化得到的JSON字符串</returns>
        public static string ToJson(this object obj)
        {
            DefaultJsonSerializer serializer = ObjectFactory.New <DefaultJsonSerializer>();

            return(serializer.Serialize(obj, false));
        }
예제 #31
0
        /// <summary>
        /// 将一个对象序列化为JSON字符串。
        /// </summary>
        /// <param name="obj">要序列化的对象</param>
        /// <param name="keepType">尽量在序列化过程中保留类型信息(Newtonsoft.Json可支持)</param>
        /// <returns>序列化得到的JSON字符串</returns>
        public static string ToJson(this object obj, bool keepType)
        {
            DefaultJsonSerializer serializer = ObjectFactory.New <DefaultJsonSerializer>();

            return(serializer.Serialize(obj, keepType));
        }
예제 #32
0
        public void Should_use_wcf_datetimeformat_when_iso8601dateformat_local_override_is_false()
        {
            // Given
            var environment = GetTestableEnvironment(x => x.Json());
            var sut = new DefaultJsonSerializer(environment) { ISO8601DateFormat = false };
            var input = new
            {
                UnspecifiedDateTime = new DateTime(2014, 3, 9, 17, 03, 25).AddMilliseconds(234),
                LocalDateTime = new DateTime(2014, 3, 9, 17, 03, 25, DateTimeKind.Local).AddMilliseconds(234),
                UtcDateTime = new DateTime(2014, 3, 9, 16, 03, 25, DateTimeKind.Utc).AddMilliseconds(234)
            };

            // When
            var output = new MemoryStream();
            sut.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            var ticks = (input.LocalDateTime.ToUniversalTime().Ticks - InitialJavaScriptDateTicks) / (long)10000;
            actual.ShouldEqual(string.Format(@"{{""unspecifiedDateTime"":""\/Date({0}{1})\/"",""localDateTime"":""\/Date({0}{1})\/"",""utcDateTime"":""\/Date(1394381005234)\/""}}",
                ticks, GetTimezoneSuffix(input.LocalDateTime)));
        }
예제 #33
0
        public void Should_use_iso8601_datetimes_by_default()
        {
            // Given
            var serializer = new DefaultJsonSerializer(GetTestableEnvironment());
            var input = new
            {
                UnspecifiedDateTime = new DateTime(2014, 3, 9, 17, 03, 25).AddMilliseconds(234),
                LocalDateTime = new DateTime(2014, 3, 9, 17, 03, 25, DateTimeKind.Local).AddMilliseconds(234),
                UtcDateTime = new DateTime(2014, 3, 9, 16, 03, 25, DateTimeKind.Utc).AddMilliseconds(234)
            };

            // When
            var output = new MemoryStream();
            serializer.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            actual.ShouldEqual(string.Format(@"{{""unspecifiedDateTime"":""2014-03-09T17:03:25.2340000{0}"",""localDateTime"":""2014-03-09T17:03:25.2340000{0}"",""utcDateTime"":""2014-03-09T16:03:25.2340000Z""}}",
                GetTimezoneSuffix(input.LocalDateTime, ":")));
        }
        public void Should_camel_case_property_names_if_local_override_is_set()
        {
            JsonSettings.RetainCasing = true;
            try
            {
                // Given
                var sut = new DefaultJsonSerializer { RetainCasing = false };
                var input = new { FirstName = "Joe", lastName = "Doe" };

                // When
                var output = new MemoryStream();
                sut.Serialize("application/json", input, output);
                var actual = Encoding.UTF8.GetString(output.ToArray());

                // Then
                actual.ShouldEqual("{\"firstName\":\"Joe\",\"lastName\":\"Doe\"}");
            }
            finally
            {
                JsonSettings.RetainCasing = false;
            }
        }