Exemplo n.º 1
0
        public void Test_enum_overloads()
        {
            JsConfig <Person> .EmitCamelCaseNames = true;
            JsConfig.IncludeNullValues            = true;
            JsConfig <PersonStatus> .SerializeFn  = text => text.ToString().ToCamelCase();

            var dto = new Person {
                Status = PersonStatus.ActiveAgent
            };

            var json = JsonSerializer.SerializeToString(dto);

            Assert.That(json, Is.EqualTo("{\"status\":\"activeAgent\"}"));

            Console.WriteLine(json);

            JsConfig.Reset();
        }
        public void Serialize_can_include_null_values()
        {
            var o = new NullValueTester
            {
                Name             = "Brandon",
                Type             = "Programmer",
                SampleKey        = 12,
                Nothing          = null,
                NullClass        = null,
                NullableDateTime = null,
            };

            JsConfig.IncludeNullValues = true;
            var s = JsonSerializer.SerializeToString(o);

            JsConfig.Reset();
            Assert.That(s, Is.EqualTo("{\"Name\":\"Brandon\",\"Type\":\"Programmer\",\"SampleKey\":12,\"Nothing\":null,\"NullClass\":null,\"NullableDateTime\":null}"));
        }
        public void Can_serialize_json_date_timestampOffset_local()
        {
            JsConfig.DateHandler = JsonDateHandler.TimestampOffset;

            var dateTime = new DateTime(1994, 11, 24, 0, 0, 0, DateTimeKind.Local);
            var ssJson   = JsonSerializer.SerializeToString(dateTime);

#if !NETCF
            var offsetSpan = TimeZoneInfo.Local.GetUtcOffset(dateTime);
#else
            var offsetSpan = TimeZone.CurrentTimeZone.GetUtcOffset(dateTime);
#endif
            var ticks  = 785635200000 - offsetSpan.TotalMilliseconds;
            var offset = offsetSpan.ToTimeOffsetString();

            Assert.That(ssJson, Is.EqualTo(@"""\/Date(" + ticks + offset + @")\/"""));
            JsConfig.Reset();
        }
Exemplo n.º 4
0
        public void Test_override_DeserializeFn()
        {
            JsConfig <bool?> .DeSerializeFn = value => string.IsNullOrEmpty(value) ? (bool?)null : bool.Parse(value);
            JsConfig <int?> .DeSerializeFn  = value => string.IsNullOrEmpty(value) ? (int?)null : int.Parse(value);
            JsConfig <long?> .DeSerializeFn = value => string.IsNullOrEmpty(value) ? (long?)null : long.Parse(value);
            JsConfig <Guid?> .DeSerializeFn = value => string.IsNullOrEmpty(value) ? (Guid?)null : new Guid(value);

            try {
                var json     = "{\"intValue\":1,\"boolValue\":\"\",\"longValue\":null}";
                var fromJson = json.FromJson <EntityForOverridingDeserialization>();
                Assert.That(fromJson.IntValue, Is.EqualTo(1));
                Assert.That(fromJson.BoolValue, Is.Null);
                Assert.That(fromJson.LongValue, Is.Null);
                Assert.That(fromJson.GuidValue, Is.Null);
            } finally {
                JsConfig.Reset();
            }
        }
Exemplo n.º 5
0
        public void Does_call_RawSerializeFn_for_toplevel_types()
        {
            JsConfig <ICar> .RawSerializeFn = SerializeCar;

            var luxaryParent = new Parent()
            {
                Car = new LuxaryCar()
                {
                    Sunroof = "Big"
                }
            };
            var cheapParent = new Parent()
            {
                Car = new CheapCar()
                {
                    HasCupHolder = true
                }
            };

            // Works when ICar is a child
            var luxaryParentJson = luxaryParent.ToJson();
            var cheapParentJson  = cheapParent.ToJson();

            Assert.That(luxaryParentJson, Is.Not.StringContaining("__type"));
            Assert.That(cheapParentJson, Is.Not.StringContaining("__type"));

            ICar luxary = new LuxaryCar()
            {
                Sunroof = "Big"
            };
            ICar cheap = new CheapCar()
            {
                HasCupHolder = true
            };

            // ToJson() loses runtime cast of interface type, to keep it we need to specify it on call-site
            var luxaryJson = JsonSerializer.SerializeToString(luxary, typeof(ICar));
            var cheapJson  = JsonSerializer.SerializeToString(cheap, typeof(ICar));

            Assert.That(luxaryJson, Is.Not.StringContaining("__type"));
            Assert.That(cheapJson, Is.Not.StringContaining("__type"));

            JsConfig.Reset();
        }
        /// <summary>
        /// The main program executes the tests. Output may be routed to
        /// various locations, depending on the arguments passed.
        /// </summary>
        /// <remarks>Run with --help for a full list of arguments supported</remarks>
        /// <param name="args"></param>
        public static int Main(string[] args)
        {
            var licenseKey = Environment.GetEnvironmentVariable("SERVICESTACK_LICENSE");

            if (licenseKey.IsNullOrEmpty())
            {
                throw new ArgumentNullException("SERVICESTACK_LICENSE", "Add Environment variable for SERVICESTACK_LICENSE");
            }

            Licensing.RegisterLicense(licenseKey);
            //"ActivatedLicenseFeatures: ".Print(LicenseUtils.ActivatedLicenseFeatures());

            CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US");
            JsConfig.Reset();
            //JsonServiceClient client = new JsonServiceClient();
            var writer = new ExtendedTextWrapper(Console.Out);

            return(new AutoRun(((IReflectableType)typeof(NetCoreTestsRunner)).GetTypeInfo().Assembly).Execute(args, writer, Console.In));
        }
Exemplo n.º 7
0
        public void Can_TreatValueAsRefType()
        {
            JsConfig <UserStruct> .TreatValueAsRefType = true;

            var dto = new UserStruct {
                Id = 1, Name = "foo"
            };

            Assert.That(dto.ToJson(),
                        Is.EqualTo("{\"Id\":1,\"Name\":\"foo\"}"));

            Assert.That(dto.ToJsv(),
                        Is.EqualTo("{Id:1,Name:foo}"));
#if !XBOX && !SILVERLIGHT && !MONOTOUCH
            Assert.That(dto.ToXml(),
                        Is.EqualTo("<?xml version=\"1.0\" encoding=\"utf-8\"?><UserStruct xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/NServiceKit.Text.Tests\"><Id>1</Id><Name>foo</Name></UserStruct>"));
#endif
            JsConfig.Reset();
        }
        public void Can_serialize_custom_ints()
        {
            //JsConfig<int>.IncludeDefaultValue = true;
            JsConfig <int> .RawSerializeFn = i =>
                                             i == 0 ? "-1" : i.ToString();

            var dto = new ModelInt {
                Int = 0
            };

            using (JsConfig.With(new Config {
                IncludeNullValues = true
            }))
            {
                Assert.That(dto.ToJson(), Is.EqualTo("{\"Int\":-1}"));
            }

            JsConfig.Reset();
        }
Exemplo n.º 9
0
        public void Can_Serialize_AnonymousTypeProperties_WithCustomFunction()
        {
            var test = new { Name = "Test", Data = new byte[] { 1, 2, 3, 4, 5 } };

            // Act: now we set a custom function for byte[]
            JsConfig <byte[]> .RawSerializeFn = c =>
            {
                var temp = new int[c.Length];
                Array.Copy(c, temp, c.Length);
                return(JsonSerializer.SerializeToString(temp));
            };
            var json = JsonSerializer.SerializeToString(test);

            // Assert:
            Assert.That(json, Is.EquivalentTo("{\"Name\":\"Test\",\"Data\":[1,2,3,4,5]}"));

            JsConfig <byte[]> .RawSerializeFn = null;
            JsConfig.Reset();
        }
        public void Reset_ShouldClear_JsConfigT_CachedFunctions()
        {
            var test = new { Name = "Test", Data = new byte[] { 1, 2, 3, 4, 5 } };

            JsConfig <byte[]> .RawSerializeFn = c =>
            {
                var temp = new int[c.Length];
                Array.Copy(c, temp, c.Length);
                return(JsonSerializer.SerializeToString(temp));
            };
            var json = JsonSerializer.SerializeToString(test);

            Assert.That(json, Is.EquivalentTo("{\"Name\":\"Test\",\"Data\":[1,2,3,4,5]}"));
            // Act: now we set a custom function for byte[]
            JsConfig.Reset();
            json = JsonSerializer.SerializeToString(test);
            // Assert:
            Assert.That(json, Is.EquivalentTo("{\"Name\":\"Test\",\"Data\":\"AQIDBAU=\"}"));
        }
Exemplo n.º 11
0
        public void Can_GetKeysByPattern()
        {
            if (!(Cache is ICacheClientExtended))
            {
                return;
            }

            ((PocoDynamo)((DynamoDbCacheClient)Cache).Dynamo).PagingLimit = 2;

            JsConfig.ExcludeTypeInfo = true;

            5.Times(i => {
                IAuthSession session = new CustomAuthSession
                {
                    Id         = "sess-" + i,
                    UserAuthId = i.ToString(),
                    Custom     = "custom" + i
                };

                var sessionKey = SessionFeature.GetSessionKey(session.Id);
                Cache.Set(sessionKey, session, SessionFeature.DefaultSessionExpiry);
                Cache.Set("otherkey" + i, i);
            });

            var sessionPattern = IdUtils.CreateUrn <IAuthSession>("");

            Assert.That(sessionPattern, Is.EqualTo("urn:iauthsession:"));
            var sessionKeys = Cache.GetKeysStartingWith(sessionPattern).ToList();

            Assert.That(sessionKeys.Count, Is.EqualTo(5));
            Assert.That(sessionKeys.All(x => x.StartsWith("urn:iauthsession:")));

            var allSessions = Cache.GetAll <IAuthSession>(sessionKeys);

            Assert.That(allSessions.Values.Count(x => x != null), Is.EqualTo(sessionKeys.Count));

            var allKeys = Cache.GetAllKeys().ToList()
                          .Where(x => x.StartsWith("urn:iauthsession:") || x.StartsWith("otherkey")).ToList();

            Assert.That(allKeys.Count, Is.EqualTo(10));

            JsConfig.Reset();
        }
Exemplo n.º 12
0
        public void Throws_on_incorrect_type_with_data_set()
        {
            JsConfig.Reset();
            JsConfig.ThrowOnError = true;

            try
            {
                string json = @"{""idBad"":""abc"", ""idGood"":""2"" }";
                JsonSerializer.DeserializeFromString(json, typeof(TestDto));
                Assert.Fail("Exception should have been thrown.");
            }
            catch (SerializationException ex)
            {
                Assert.That(ex.Data, Is.Not.Null);
                Assert.That(ex.Data["propertyName"], Is.EqualTo("idBad"));
                Assert.That(ex.Data["propertyValueString"], Is.EqualTo("abc"));
                Assert.That(ex.Data["propertyType"], Is.EqualTo(typeof(int)));
            }
        }
Exemplo n.º 13
0
        public async Task Can_GetKeysByPattern()
        {
            if (!(Cache is ICacheClientExtended))
            {
                return;
            }

            JsConfig.ExcludeTypeInfo = true;

            for (int i = 0; i < 5; i++)
            {
                IAuthSession session = new CustomAuthSession
                {
                    Id         = "sess-" + i,
                    UserAuthId = i.ToString(),
                    Custom     = "custom" + i
                };

                var sessionKey = SessionFeature.GetSessionKey(session.Id);
                await Cache.SetAsync(sessionKey, session, SessionFeature.DefaultSessionExpiry);

                await Cache.SetAsync("otherkey" + i, i);
            }

            var sessionPattern = IdUtils.CreateUrn <IAuthSession>("");

            Assert.That(sessionPattern, Is.EqualTo("urn:iauthsession:"));
#if !NETFX
            var sessionKeys = await Cache.GetKeysStartingWithAsync(sessionPattern).ToListAsync();

            Assert.That(sessionKeys.Count, Is.EqualTo(5));
            Assert.That(sessionKeys.All(x => x.StartsWith("urn:iauthsession:")));

            var allSessions = await Cache.GetAllAsync <IAuthSession>(sessionKeys);

            Assert.That(allSessions.Values.Count(x => x != null), Is.EqualTo(sessionKeys.Count));

            var allKeys = (await Cache.GetAllKeysAsync().ToListAsync()).ToList();
            Assert.That(allKeys.Count, Is.EqualTo(10));
#endif
            JsConfig.Reset();
        }
Exemplo n.º 14
0
        public void Deserializes_floats_into_to_best_fit_floating_point()
        {
            JsConfig.TryToParsePrimitiveTypeValues    = true;
            JsConfig.TryToParseNumericType            = true;
            JsConfig.ParsePrimitiveFloatingPointTypes = ParseAsType.Single | ParseAsType.Double;

            float floatValue = 1.1f;
            //TODO find a number that doesn't suck which throws in float.Parse() but not double.Parse()
            double Offset      = Math.Pow(2, 1000);
            double doubleValue = double.MaxValue - Offset;
            var    intValue    = int.MaxValue;
            var    longValue   = long.MaxValue;

            float notFloat;

            Assert.That(!float.TryParse(doubleValue.ToString(), out notFloat));

            var toFloatValue = float.Parse(floatValue.ToString());

            Assert.AreEqual(toFloatValue, floatValue, 1);
            var toDoubleValue = double.Parse(doubleValue.ToString());

            Assert.AreEqual(toDoubleValue, doubleValue, Offset);

            var json = "{{\"float\":{0},\"double\":{1},\"int\":{2},\"long\":{3}}}"
                       .Fmt(CultureInfo.InvariantCulture, floatValue, doubleValue, intValue, longValue);
            var map = JsonSerializer.DeserializeFromString <IDictionary <string, object> >(json);

            Assert.That(map["float"], Is.TypeOf <float>());
            Assert.That(map["float"], Is.EqualTo(floatValue));

            Assert.That(map["double"], Is.TypeOf <double>());
            Assert.AreEqual((double)map["double"], doubleValue, Offset);

            Assert.That(map["int"], Is.TypeOf <int>());
            Assert.That(map["int"], Is.EqualTo(intValue));

            Assert.That(map["long"], Is.TypeOf <long>());
            Assert.That(map["long"], Is.EqualTo(longValue));

            JsConfig.Reset();
        }
Exemplo n.º 15
0
        public void Can_deserialize_json_date_iso8601_withOffset_asLocal()
        {
            JsConfig.DateHandler = JsonDateHandler.ISO8601;

            var dateTime = new DateTime(1994, 11, 24, 12, 34, 56, DateTimeKind.Local);

#if !NETCF
            var offset = TimeZoneInfo.Local.GetUtcOffset(dateTime).ToTimeOffsetString(":");
#else
            var offset = TimeZone.CurrentTimeZone.GetUtcOffset(dateTime).ToTimeOffsetString(":");
#endif

            var json     = @"""1994-11-24T12:34:56" + offset + @"""";
            var fromJson = JsonSerializer.DeserializeFromString <DateTime>(json);


            Assert.That(fromJson, Is.EqualTo(dateTime));
            Assert.That(fromJson.Kind, Is.EqualTo(dateTime.Kind));
            JsConfig.Reset();
        }
        public void Can_Serialize_NullsWhenNull()
        {
            var m1 = new ModelWithComplexTypes();

            JsConfig.IncludeNullValues = true;
            var s = JsonSerializer.SerializeToString(m1);

            Console.WriteLine(s);

            var m2 = new JavaScriptSerializer().Deserialize <ModelWithComplexTypes>(s);

            JsConfig.Reset();

            Assert.IsNull(m2.DictionaryValue);
            Assert.IsNull(m2.ListValue);
            Assert.IsNull(m2.ArrayValue);
            Assert.IsNull(m2.NestedTypeValue);
            Assert.IsNull(m2.ByteArrayValue);
            Assert.IsNull(m2.DateTimeValue);
        }
        public void TestThrows()
        {
            JsConfig.Reset();
            JsConfig.ThrowOnDeserializationError = true;

            string json = @"{""idBad"":""abc"", ""idGood"":""2"" }";

            bool threw = false;

            try
            {
                JsonSerializer.DeserializeFromString(json, typeof(TestDto));
            }
            catch (Exception)
            {
                threw = true;
            }

            Assert.IsTrue(threw, "Should have thrown");
        }
Exemplo n.º 18
0
        public void ConfigEnumSerializers_EnumType_JsConfigFuncsSet()
        {
            //Inspecting static values, so locking in cases tests are multi threaded.
            lock (StaticTestingLocks.JsConfigLockObject)
            {
                JsConfig <FakeTestingEnum> .Reset();

                //Testing static class is fun
                var proxy = new EnumSerializerInitializerProxy();
                proxy.ConfigEnumSerializers(typeof(FakeTestingEnum));
                //new EnumSerializerHelpers<FakeTestingEnum>();
                Func <FakeTestingEnum, string> expectedSerializeFunc =
                    PrettyEnumHelpers <FakeTestingEnum> .GetOptimalEnumDescription;
                Func <string, FakeTestingEnum> expectedDeserializeFunc =
                    PrettyEnumHelpers <FakeTestingEnum> .GetEnumFrom;

                Assert.Equal(expectedSerializeFunc, JsConfig <FakeTestingEnum> .SerializeFn);
                Assert.Equal(expectedDeserializeFunc, JsConfig <FakeTestingEnum> .DeSerializeFn);
            }
        }
Exemplo n.º 19
0
        public void Configure_TestAssembly_JsConfigFuncsSet()
        {
            //Inspecting static values, so locking in cases tests are multi threaded.
            lock (StaticTestingLocks.JsConfigLockObject)
            {
                JsConfig <FakeTestingEnum> .Reset();

                new EnumSerializerConfigurator()
                .WithAssemblies(new[] { Assembly.GetExecutingAssembly() })
                .Configure();

                Func <FakeTestingEnum, string> expectedSerializeFunc =
                    PrettyEnumHelpers <FakeTestingEnum> .GetOptimalEnumDescription;
                Func <string, FakeTestingEnum> expectedDeserializeFunc =
                    PrettyEnumHelpers <FakeTestingEnum> .GetEnumFrom;

                Assert.Equal(expectedSerializeFunc, JsConfig <FakeTestingEnum> .SerializeFn);
                Assert.Equal(expectedDeserializeFunc, JsConfig <FakeTestingEnum> .DeSerializeFn);
            }
        }
Exemplo n.º 20
0
        public void Can_serialise_polymorphic_entity_with_customised_typename()
        {
            try
            {
                JsConfig.TypeWriter = type => type.Name;

                Animal dog = new Dog {
                    Name = @"Fido", DogBark = "woof"
                };
                var asText = JsonSerializer.SerializeToString(dog);

                Log(asText);

                Assert.That(asText,
                            Is.EqualTo(
                                "{\"__type\":\"Dog\",\"Name\":\"Fido\",\"DogBark\":\"woof\"}"));
            } finally {
                JsConfig.Reset();
            }
        }
Exemplo n.º 21
0
        public void Can_deserialise_polymorphic_list_serialized_by_datacontractjsonserializer()
        {
            Func <string, Type> typeFinder = value => {
                var regex    = new Regex(@"^(?<type>[^:]+):#(?<namespace>.*)$");
                var match    = regex.Match(value);
                var typeName = string.Format("{0}.{1}", match.Groups["namespace"].Value, match.Groups["type"].Value.Replace(".", "+"));
                return(AssemblyUtils.FindType(typeName));
            };

            try {
                var originalList = new List <Animal> {
                    new Dog {
                        Name = "Fido"
                    }, new Cat {
                        Name = "Tigger"
                    }
                };

                var dataContractJsonSerializer = new DataContractJsonSerializer(typeof(List <Animal>), new[] { typeof(Dog), typeof(Cat) }, int.MaxValue, true, null, true);
                JsConfig.TypeFinder = typeFinder;
                List <Animal> deserializedList = null;
                using (var stream = new MemoryStream()) {
                    dataContractJsonSerializer.WriteObject(stream, originalList);
                    stream.Position = 0;
                    using (var reader = new StreamReader(stream)) {
                        var json = reader.ReadToEnd();
                        deserializedList = JsonSerializer.DeserializeFromString <List <Animal> >(json);
                    }
                }

                Assert.That(deserializedList.Count, Is.EqualTo(originalList.Count));

                Assert.That(deserializedList[0].GetType(), Is.EqualTo(originalList[0].GetType()));
                Assert.That(deserializedList[1].GetType(), Is.EqualTo(originalList[1].GetType()));

                Assert.That(deserializedList[0].Name, Is.EqualTo(originalList[0].Name));
                Assert.That(deserializedList[1].Name, Is.EqualTo(originalList[1].Name));
            } finally {
                JsConfig.Reset();
            }
        }
        public void Can_serialize_custom_doubles()
        {
            JsConfig <double> .IncludeDefaultValue = true;
            JsConfig <double> .RawSerializeFn      = d =>
                                                     double.IsPositiveInfinity(d) ?
                                                     "\"+Inf\""
                : double.IsNegativeInfinity(d) ?
                                                     "\"-Inf\""
                : double.IsNaN(d) ?
                                                     "\"NaN\""
                : d.ToString();

            var doubles = new[] { 0.0, 1.0, double.NegativeInfinity, double.NaN, double.PositiveInfinity };

            Assert.That(doubles.ToJson(), Is.EqualTo("[0,1,\"-Inf\",\"NaN\",\"+Inf\"]"));

            Assert.That(new KeyValuePair <double, double>(0, 1).ToJson(),
                        Is.EqualTo("{\"Key\":0,\"Value\":1}"));

            JsConfig.Reset();
        }
Exemplo n.º 23
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                //clear managed resources here
                foreach (var callback in OnDisposeCallbacks)
                {
                    callback(this);
                }

                if (Container != null)
                {
                    Container.Dispose();
                    Container = null;
                }

                JsConfig.Reset(); //Clears Runtime Attributes

                Instance = null;
            }
            //clear unmanaged resources here
        }
Exemplo n.º 24
0
        public void Can_deserialise_polymorphic_list_serialized_by_newtonsoft()
        {
            var json =
                "[{\"$type\":\""
                + typeof(Dog).ToTypeString()
                + "\",\"Name\":\"Fido\"},{\"$type\":\""
                + typeof(Cat).ToTypeString()
                + "\",\"Name\":\"Tigger\"}}]";

            try {
                var originalList = new List <Animal> {
                    new Dog {
                        Name = "Fido"
                    }, new Cat {
                        Name = "Tigger"
                    }
                };

                //var newtonsoftSerializer = new Newtonsoft.Json.JsonSerializer { TypeNameHandling = TypeNameHandling.All };
                //var buffer = new StringBuilder();
                //using (var writer = new StringWriter(buffer)) {
                //    newtonsoftSerializer.Serialize(writer, originalList);
                //}
                //var json = buffer.ToString();

                JsConfig.TypeAttr = "$type";
                var deserializedList = JsonSerializer.DeserializeFromString <List <Animal> >(json);

                Assert.That(deserializedList.Count, Is.EqualTo(originalList.Count));

                Assert.That(deserializedList[0].GetType(), Is.EqualTo(originalList[0].GetType()));
                Assert.That(deserializedList[1].GetType(), Is.EqualTo(originalList[1].GetType()));

                Assert.That(deserializedList[0].Name, Is.EqualTo(originalList[0].Name));
                Assert.That(deserializedList[1].Name, Is.EqualTo(originalList[1].Name));
            } finally {
                JsConfig.Reset();
            }
        }
        public void Can_deserialise_an_entity_containing_a_polymorphic_property_serialized_by_datacontractjsonserializer()
        {
            Func <string, Type> typeFinder = value => {
                var regex    = new Regex(@"^(?<type>[^:]+):#(?<namespace>.*)$");
                var match    = regex.Match(value);
                var typeName = string.Format("{0}.{1}", match.Groups["namespace"].Value, match.Groups["type"].Value.Replace(".", "+"));
                return(Type.GetType(typeName));
            };

            try {
                var originalPets = new Pets {
                    Cat = new Cat {
                        Name = "Tigger"
                    }, Dog = new Dog {
                        Name = "Fido"
                    }
                };

                var dataContractJsonSerializer = new DataContractJsonSerializer(typeof(Pets), new[] { typeof(Dog), typeof(Cat) }, int.MaxValue, true, null, true);
                JsConfig.TypeFinder = typeFinder;
                Pets deserializedPets = null;
                using (var stream = new MemoryStream()) {
                    dataContractJsonSerializer.WriteObject(stream, originalPets);
                    stream.Position = 0;
                    using (var reader = new StreamReader(stream)) {
                        var json = reader.ReadToEnd();
                        deserializedPets = JsonSerializer.DeserializeFromString <Pets>(json);
                    }
                }

                Assert.That(deserializedPets.Cat.GetType(), Is.EqualTo(originalPets.Cat.GetType()));
                Assert.That(deserializedPets.Dog.GetType(), Is.EqualTo(originalPets.Dog.GetType()));

                Assert.That(deserializedPets.Cat.Name, Is.EqualTo(originalPets.Cat.Name));
                Assert.That(deserializedPets.Dog.Name, Is.EqualTo(originalPets.Dog.Name));
            } finally {
                JsConfig.Reset();
            }
        }
        public void Can_deserialize_using_CustomFormat()
        {
            var test = new DcStatus {
                Voltage = 10, Current = 1.2
            };

            Assert.That(test.ToJson(), Is.EqualTo("{\"Voltage\":\"10.0 V\",\"Current\":\"1.200 A\",\"Power\":\"12 W\"}"));

            JsConfig <DcStatusRawFn> .RawSerializeFn = o => new Dictionary <string, string> {
                { "Voltage", string.Format(CultureInfo.InvariantCulture, "{0:0.0} V", o.Voltage) },
                { "Current", string.Format(CultureInfo.InvariantCulture, "{0:0.000} A", o.Current) },
                { "Power", $"{o.Power:0} W" },
            }.ToJson();

            var test2 = new DcStatusRawFn {
                Voltage = 10, Current = 1.2
            };

            Assert.That(test2.ToJson(), Is.EqualTo("{\"Voltage\":\"10.0 V\",\"Current\":\"1.200 A\",\"Power\":\"12 W\"}"));

            JsConfig.Reset();
        }
Exemplo n.º 27
0
        public void Should_write_serialized_object_to_stream_using_date_handler()
        {
            var formatter = new ServiceStackTextFormatter(JsonDateHandler.TimestampOffset);
            var value     = GetTestObject();

            var contentHeader = new StringContent(string.Empty).Headers;

            contentHeader.Clear();
            var memoryStream = new MemoryStream();

            var resultTask = formatter.WriteToStreamAsync(typeof(RootClass), value, memoryStream, contentHeader, transportContext: null);

            resultTask.Wait();

            memoryStream.Position = 0;
            string serializedString = new StreamReader(memoryStream).ReadToEnd();

            JsConfig.DateHandler = JsonDateHandler.TimestampOffset;
            var expected = value.ToJson();

            JsConfig.Reset();
            serializedString.ShouldEqual(expected);
        }
Exemplo n.º 28
0
        public void Can_serialize_custom_DateTime2()
        {
            JsConfig <DateTime> .SerializeFn = time =>
            {
                var x = new DateTime(time.Ticks, DateTimeKind.Unspecified).ToString("o");
                return(x);
            };

            JsConfig <DateTime> .DeSerializeFn = time =>
            {
                var x = DateTime.ParseExact(time, "o", null);
                return(x);
            };

            var dateTime = new DateTime(2015, 08, 12, 12, 12, 12, DateTimeKind.Unspecified);

            var json = dateTime.ToJson();

            Assert.That(json, Is.EqualTo("\"2015-08-12T12:12:12.0000000\""));

            var fromJson = json.FromJson <DateTime>();

            Assert.That(fromJson, Is.EqualTo(dateTime));

            var dto = new Response
            {
                DateTime = dateTime,
            };

            json = dto.ToJson();
            Assert.That(json, Is.EqualTo("{\"DateTime\":\"2015-08-12T12:12:12.0000000\"}"));
            Assert.That(json.FromJson <Response>().DateTime, Is.EqualTo(dateTime));

            JsConfig <DateTime> .SerializeFn   = null;
            JsConfig <DateTime> .DeSerializeFn = null;
            JsConfig.Reset();
        }
Exemplo n.º 29
0
        public void ServiceStack_AllowRuntimeType()
        {
            // Initialize static delegate to allow all types to be deserialized with the type attribute
            JsConfig.AllowRuntimeType = _ => true;
            JsConfig.TypeAttr         = "$type";
            var example = new Example {
                Property = new MyProperty {
                    Value = "Hello serializer"
                }
            };

            var serialized   = JsonSerializer.SerializeToString(example);
            var deserialized = JsonSerializer.DeserializeFromString <Example>(serialized);

            Assert.IsNotNull(deserialized?.Property);

            // Now the same process with a config scope that has a TypeAttr that differs from the global TypeAttr value
            using var scope = JsConfig.With(new Config { TypeAttr = "_type" });
            serialized      = JsonSerializer.SerializeToString(example);
            deserialized    = JsonSerializer.DeserializeFromString <Example>(serialized);
            Assert.IsNotNull(deserialized?.Property);

            JsConfig.Reset();
        }
Exemplo n.º 30
0
        public void Can_deserialise_an_entity_containing_a_polymorphic_property_serialized_by_newtonsoft()
        {
            var json =
                "{\"$type\":\""
                + typeof(Pets).ToTypeString()
                + "\",\"Dog\":{\"$type\":\""
                + typeof(Dog).ToTypeString()
                + "\",\"Name\":\"Fido\"},\"Cat\":{\"$type\":\""
                + typeof(Cat).ToTypeString()
                + "\",\"Name\":\"Tigger\"}}";

            try {
                JsConfig.TypeAttr = "$type";
                var deserializedPets = JsonSerializer.DeserializeFromString <Pets>(json);

                Assert.That(deserializedPets.Cat.GetType(), Is.EqualTo(typeof(Cat)));
                Assert.That(deserializedPets.Dog.GetType(), Is.EqualTo(typeof(Dog)));

                Assert.That(deserializedPets.Cat.Name, Is.EqualTo("Tigger"));
                Assert.That(deserializedPets.Dog.Name, Is.EqualTo("Fido"));
            } finally {
                JsConfig.Reset();
            }
        }