public void CustomDefaultConverter_NumericStyle_ReadsCurrencyAsNumber()
        {
            var expected = new Money(14.3m, CurrencyIsoCode.XTS);

            string json = "{\"Amount\":14.3,\"Currency\":963}";

            using (new ConfigScope(DefaultMoneySerializer.Numeric.Deserialize, JsConfig.With(emitCamelCaseNames: false)))
            {
                var actual = JsonSerializer.DeserializeFromString <Money>(json);

                Assert.That(actual, Is.EqualTo(expected));
            }
        }
Example #2
0
 public GetTopicResponse GetTopic(int id)
 {
     using (JsConfig
            .With(propertyConvention: PropertyConvention.Lenient,
                  emitLowercaseUnderscoreNames: true,
                  emitCamelCaseNames: false))
     {
         var request = new GetTopic {
             TopicId = id
         };
         return(client.Get(request));
     }
 }
        public void CustomCurrencyLessConverter_WithCamelCase_ReadsCamelCasedProperties()
        {
            var expected = new Money(14.3m, CurrencyIsoCode.XXX);

            string json = "{\"Name\": \"something\", \"PropName\":14.3}";

            using (new ConfigScope(CurrencyLessMoneySerializer.Deserialize, JsConfig.With(emitCamelCaseNames: true)))
            {
                var actual = JsonSerializer.DeserializeFromString <MoneyContainer>(json);

                Assert.That(actual.PropName, Is.EqualTo(expected));
            }
        }
        public void CustomDefaultConverter_WithCamelCase_ReadsCamelCasedProperties()
        {
            var expected = new Money(14.3m, CurrencyIsoCode.XTS);

            string json = "{\"amount\":14.3,\"currency\":\"XTS\"}";

            using (new ConfigScope(DefaultMoneySerializer.Deserialize, JsConfig.With(emitCamelCaseNames: true)))
            {
                var actual = JsonSerializer.DeserializeFromString <Money>(json);

                Assert.That(actual, Is.EqualTo(expected));
            }
        }
Example #5
0
 public void Can_serialize_NullTimeSpan_field_with_StandardTimeSpanFormat()
 {
     using (JsConfig.With(new Config {
         TimeSpanHandler = TimeSpanHandler.StandardFormat
     }))
     {
         var model = new NullableSampleModel {
             Id = 1
         };
         var json = JsonSerializer.SerializeToString(model);
         Assert.That(json, Does.Not.Contain("\"TimeSpan\""));
     }
 }
Example #6
0
        public void Can_serialize_NullableTimeSpan_field_with_StandardTimeSpanFormat()
        {
            using (JsConfig.With(timeSpanHandler: TimeSpanHandler.StandardFormat))
            {
                var period = TimeSpan.FromSeconds(70);

                var model = new NullableSampleModel {
                    Id = 1, TimeSpan = period
                };
                var json = JsonSerializer.SerializeToString(model);
                Assert.That(json, Is.StringContaining("\"TimeSpan\":\"00:01:10\""));
            }
        }
Example #7
0
 public object Post(CreateEmailInstance request)
 {
     return(WithDb(db =>
     {
         var entity = request.ConvertTo <Email>();
         return new HttpResult(new CommonResponse(Logic.CreateInstance(entity)))
         {
             ResultScope = () => JsConfig.With(new Config {
                 IncludeNullValues = true
             })
         };
     }));
 }
Example #8
0
        public object Get(SwaggerResource request)
        {
            var path  = "/" + request.Name;
            var map   = HostContext.ServiceController.RestPathMap;
            var paths = new List <RestPath>();

            var basePath = base.Request.GetBaseUrl();

            var meta = HostContext.Metadata;

            foreach (var key in map.Keys)
            {
                var restPaths     = map[key];
                var selectedPaths = restPaths.Where(x => x.Path == path || x.Path.StartsWith(path + "/"));
                var visiblePaths  = selectedPaths.Where(x => meta.IsVisible(Request, Format.Json, x.RequestType.Name));
                paths.AddRange(visiblePaths);
            }

            var models = new Dictionary <string, SwaggerModel>();

            foreach (var restPath in paths.SelectMany(x => x.Verbs.Select(y => new { Value = x, Verb = y })))
            {
                ParseModel(models, restPath.Value.RequestType, restPath.Value.Path, restPath.Verb);
            }

            var apis = paths.Select(p => FormatMethodDescription(p, models))
                       .ToArray().OrderBy(md => md.Path).ToList();

            var result = new SwaggerApiDeclaration
            {
                ApiVersion   = HostContext.Config.ApiVersion,
                ResourcePath = path,
                BasePath     = basePath,
                Apis         = apis,
                Models       = models
            };

            if (OperationFilter != null)
            {
                apis.Each(x => x.Operations.Each(OperationFilter));
            }

            ApiDeclarationFilter?.Invoke(result);

            return(new HttpResult(result)
            {
                ResultScope = () => JsConfig.With(new Config {
                    IncludeNullValues = false
                })
            });
        }
        public object Get(SwaggerResources request)
        {
            var basePath = base.Request.GetBaseUrl();

            var result = new SwaggerResourcesResponse
            {
                BasePath   = basePath,
                Apis       = new List <SwaggerResourceRef>(),
                ApiVersion = HostContext.Config.ApiVersion,
                Info       = new SwaggerInfo
                {
                    Title = HostContext.ServiceName,
                }
            };
            var operations        = HostContext.Metadata;
            var allTypes          = operations.GetAllOperationTypes();
            var allOperationNames = operations.GetAllOperationNames();

            foreach (var operationName in allOperationNames)
            {
                if (resourceFilterRegex != null && !resourceFilterRegex.IsMatch(operationName))
                {
                    continue;
                }
                var name          = operationName;
                var operationType = allTypes.FirstOrDefault(x => x.Name == name);
                if (operationType == null)
                {
                    continue;
                }
                if (operationType == typeof(SwaggerResources) || operationType == typeof(SwaggerResource))
                {
                    continue;
                }
                if (!operations.IsVisible(Request, Format.Json, operationName))
                {
                    continue;
                }

                CreateRestPaths(result.Apis, operationType, operationName);
            }

            result.Apis = result.Apis.OrderBy(a => a.Path).ToList();

            ResourcesResponseFilter?.Invoke(result);

            return(new HttpResult(result)
            {
                ResultScope = () => JsConfig.With(includeNullValues: false)
            });
        }
        public void Can_serialize_different_enum_styles()
        {
            Assert.That("Word".FromJson <EnumStyles>(), Is.EqualTo(EnumStyles.Word));
            Assert.That("DoubleWord".FromJson <EnumStyles>(), Is.EqualTo(EnumStyles.DoubleWord));
            Assert.That("Underscore_Words".FromJson <EnumStyles>(), Is.EqualTo(EnumStyles.Underscore_Words));

            using (JsConfig.With(new Config {
                TextCase = TextCase.SnakeCase
            }))
            {
                Assert.That("Double_Word".FromJson <EnumStyles>(), Is.EqualTo(EnumStyles.DoubleWord));
                Assert.That("Underscore_Words".FromJson <EnumStyles>(), Is.EqualTo(EnumStyles.Underscore_Words));
            }
        }
 public void Can_limit_cyclical_dependencies()
 {
     using (JsConfig.With(maxDepth: 4))
     {
         var p = new person();
         p.teacher = new person {
             name = "sam", teacher = p
         };
         p.name = "bob";
         p.PrintDump();
         p.ToJsv().Print();
         p.ToJson().Print();
     }
 }
Example #12
0
 public void KVP_Serializer_fills_public_fields()
 {
     using (JsConfig.With(new Config {
         IncludePublicFields = true
     }))
     {
         var valueMap = new Dictionary <string, string> {
             { "FirstName", "james" }, { "LastName", "bond" }, { "FullName", "james bond" }
         };
         var result = (CustomerWithFields)KeyValueDataContractDeserializer.Instance.Parse(valueMap, typeof(CustomerWithFields));
         Assert.That(result.FirstName, Is.EqualTo("james"));
         Assert.That(result.LastName, Is.EqualTo("bond"));
     }
 }
Example #13
0
        public void Can_include_null_values_for_adhoc_types()
        {
            Assert.That(new Foo().ToJson(), Is.EqualTo("{}"));

            JsConfig <Foo> .RawSerializeFn = obj =>
            {
                using (JsConfig.With(includeNullValues: true))
                    return(obj.ToJson());
            };

            Assert.That(new Foo().ToJson(), Is.EqualTo("{\"Bar\":null}"));

            JsConfig.Reset();
        }
Example #14
0
        public void CustomCanonicalConverter_WithCamelCasing_LikeCanonicalJsonSerialization()
        {
            using (var serializer = new DataContractJsonRoundtripSerializer <Money>(dataContractSurrogate: new DataContractSurrogate()))
            {
                var    toSerialize = new Money(14.3m, CurrencyIsoCode.XTS);
                string canonical   = serializer.Serialize(toSerialize);

                using (new ConfigScope(CanonicalMoneySerializer.Serialize, JsConfig.With(emitCamelCaseNames: true)))
                {
                    string actual = JsonSerializer.SerializeToString(toSerialize);
                    Assert.That(actual, Is.EqualTo(canonical));
                }
            }
        }
        public void Can_run_FromJson_within_RawDeserializeFn()
        {
            JsConfig <Foo> .RawDeserializeFn = json =>
            {
                using (JsConfig.With(new Config {
                    IncludeNullValues = true
                }))
                    return(json.FromJson <Foo>());
            };

            var obj = "{\"Bar\":\"Bar\"}".FromJson <Foo>();

            Assert.That(obj.Bar, Is.EqualTo("Bar"));
        }
Example #16
0
        public void Can_serialize_different_enum_styles()
        {
            Assert.That("Word".FromJson <EnumStyles>(), Is.EqualTo(EnumStyles.Word));
            Assert.That("DoubleWord".FromJson <EnumStyles>(), Is.EqualTo(EnumStyles.DoubleWord));
            Assert.That("Underscore_Words".FromJson <EnumStyles>(), Is.EqualTo(EnumStyles.Underscore_Words));

            using (JsConfig.With(new Config {
                EmitLowercaseUnderscoreNames = true
            }))
            {
                Assert.That("Double_Word".FromJson <EnumStyles>(), Is.EqualTo(EnumStyles.DoubleWord));
                Assert.That("Underscore_Words".FromJson <EnumStyles>(), Is.EqualTo(EnumStyles.Underscore_Words));
            }
        }
Example #17
0
        public void Can_Serialize_Array_with_nulls()
        {
            using (JsConfig.With(includeNullValues: true))
            {
                var t = new {
                    Name   = "MyName",
                    Number = (int?)null,
                    Data   = new object[] { 5, null, "text" }
                };

                var json = JsonSerializer.SerializeToString(t);
                Assert.That(json, Is.EqualTo("{\"Name\":\"MyName\",\"Number\":null,\"Data\":[5,null,\"text\"]}"));
            }
        }
Example #18
0
        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(includeNullValues: true))
            {
                Assert.That(dto.ToJson(), Is.EqualTo("{\"Int\":-1}"));
            }

            JsConfig.Reset();
        }
        public void Should_be_able_to_deserialise_based_on_an_interface_with_no_concrete()
        {
            using (JsConfig.With(preferInterfaces: true))
            {
                var json = new Concrete("boo", 42).ToJson();

                // break the typing so we have to use the dynamic implementation
                json = json.Replace("NServiceKit.Text.Tests.JsonTests.IContract", "NServiceKit.Text.Tests.JsonTests.IIdenticalContract");

                var result = JsonSerializer.DeserializeFromString <IIdenticalContract>(json);

                Assert.That(result.StringValue, Is.EqualTo("boo"));
                Assert.That(result.ChildProp.IntValue, Is.EqualTo(42));
            }
        }
Example #20
0
        public void Does_serialize_to_UnixTime_when_scoped()
        {
            var dto = new TestObject {
                Date = new DateTime(2001, 01, 01, 0, 0, 0, DateTimeKind.Utc)
            };

            using var config = JsConfig.With(new Config { DateHandler = DateHandler.UnixTime });
            var json = dto.ToJson();

            Assert.That(json, Is.EquivalentTo("{\"Date\":978307200}"));

            var fromJson = JsonSerializer.DeserializeFromString <TestObject>(json);

            Assert.That(fromJson.Date, Is.EqualTo(dto.Date));
        }
        public void Should_not_use_interface_type_if_concrete_specified()
        {
#if NETCF
            using (JsConfig.With(null, null, null, null, null, null, null, null, null, /*preferInterfaces*/ false, null, null, null, null, null, null, null, null, null, null))
#else
            using (JsConfig.With(preferInterfaces: false))
#endif
            {
                IContract myConcrete = new Concrete("boo", 1);
                var       json       = JsonSerializer.SerializeToString(myConcrete, typeof(IContract));

                Console.WriteLine(json);
                Assert.That(json, Is.StringContaining("\"ServiceStack.Text.Tests.JsonTests.Concrete, ServiceStack.Text.Tests\""));
            }
        }
        public void Should_be_able_to_serialise_based_on_an_interface()
        {
#if NETCF
            using (JsConfig.With(null, null, null, null, null, null, null, null, null, /*preferInterfaces*/ true, null, null, null, null, null, null, null, null, null, null))
#else
            using (JsConfig.With(preferInterfaces: true))
#endif
            {
                IContract myConcrete = new Concrete("boo", 1);
                var       json       = JsonSerializer.SerializeToString(myConcrete, typeof(IContract));

                Console.WriteLine(json);
                Assert.That(json, Is.StringContaining("\"ServiceStack.Text.Tests.JsonTests.IContract, ServiceStack.Text.Tests\""));
            }
        }
        public void Does_Convert_BenchSource()
        {
            var from = new BenchSource();
            var to   = from.ConvertTo <BenchDestination>(); //warmup

            to = from.ConvertTo <BenchDestination>();

            using (JsConfig.With(new Config {
                IncludePublicFields = true
            }))
            {
                to.PrintDump();
                from.PrintDump();
            }
        }
Example #24
0
        public void Can_deserialize_ComplexTypeWithFields_path()
        {
            using (JsConfig.With(includePublicFields: true))
            {
                var restPath = new RestPath(typeof(ComplexTypeWithFields),
                                            "/Complex/{Id}/{Name}/Unique/{UniqueId}");
                var request = restPath.CreateRequest(
                    "/complex/5/Is Alive/unique/4583B364-BBDC-427F-A289-C2923DEBD547") as ComplexTypeWithFields;

                Assert.That(request, Is.Not.Null);
                Assert.That(request.Id, Is.EqualTo(5));
                Assert.That(request.Name, Is.EqualTo("Is Alive"));
                Assert.That(request.UniqueId, Is.EqualTo(new Guid("4583B364-BBDC-427F-A289-C2923DEBD547")));
            }
        }
Example #25
0
 public void Deserialize_dynamic_json_with_keys_starting_with_object_literal()
 {
     using (JsConfig.With(new Config {
         ConvertObjectTypesIntoStringDictionary = true
     }))
     {
         var json = @"{""prop1"": ""value1"", ""prop2"": ""{tag} value2"", ""prop3"": { ""A"" : 1 } }";
         var obj  = json.FromJson <Dictionary <string, object> >();
         Assert.That(obj["prop1"], Is.EqualTo("value1"));
         Assert.That(obj["prop2"], Is.EqualTo("{tag} value2"));
         Assert.That(obj["prop3"], Is.EqualTo(new Dictionary <string, object> {
             ["A"] = "1"
         }));
     }
 }
Example #26
0
        public void Can_serialize_TimeSpan_field_with_StandardTimeSpanFormat()
        {
            using (JsConfig.With(new Config {
                TimeSpanHandler = TimeSpanHandler.StandardFormat
            }))
            {
                var period = TimeSpan.FromSeconds(70);

                var model = new SampleModel {
                    Id = 1, TimeSpan = period
                };
                var json = JsonSerializer.SerializeToString(model);
                Assert.That(json, Does.Contain("\"TimeSpan\":\"00:01:10\""));
            }
        }
Example #27
0
        public void CustomDefaultConverter_NumericStyle_TakesPrecedenceOverHowEnumsGetSerialized()
        {
            var toSerialize = new Money(14.3m, CurrencyIsoCode.XTS);

            using (new ConfigScope(DefaultMoneySerializer.Numeric.Serialize, JsConfig.With(treatEnumAsInteger: false)))
            {
                string actual = JsonSerializer.SerializeToString(toSerialize);
                Assert.That(actual, Is.EqualTo("{\"Amount\":14.3,\"Currency\":963}"));
            }

            using (new ConfigScope(DefaultMoneySerializer.Serialize, JsConfig.With(treatEnumAsInteger: true)))
            {
                string actual = JsonSerializer.SerializeToString(toSerialize);
                Assert.That(actual, Is.EqualTo("{\"Amount\":14.3,\"Currency\":\"XTS\"}"));
            }
        }
Example #28
0
        public object Get(GhostPostsProxyRequest req)
        {
            GhostPosts posts = null;

            var json = $"{AppSettings.Get<string>("GhostApi:BaseUrl")}/posts/?key={AppSettings.Get<string>("GhostApi:ContentKey")}&include=authors,tags&page={req.Page}&limit={req.Limit}".GetJsonFromUrl();

            using (JsConfig.With(new ServiceStack.Text.Config {
                TextCase = TextCase.SnakeCase,
                PropertyConvention = PropertyConvention.Lenient
            }))
            {
                posts = json.FromJson <GhostPosts>();
            }

            return(posts);
        }
Example #29
0
        public void Can_serialize_NullTimeSpan_field_with_StandardTimeSpanFormat()
        {
#if NETCF // TODO NETCF make perfect
            using (JsConfig.With(null, null, null, null, null, null, null, null,
                                 JsonTimeSpanHandler.StandardFormat,
                                 null, null, null, null, null, null, null, null, null, null, null))
#else
            using (JsConfig.With(timeSpanHandler: JsonTimeSpanHandler.StandardFormat))
#endif
            {
                var model = new NullableSampleModel {
                    Id = 1
                };
                var json = JsonSerializer.SerializeToString(model);
                Assert.That(json, Is.Not.StringContaining("\"TimeSpan\""));
            }
        }
 private void BufferedLogEntries(SeqRequestLogEntry entry)
 {
     // TODO add buffering to logging for perf
     // scope to force json camel casing off
     using (JsConfig.With(emitCamelCaseNames: false))
     {
         eventsUri.PostJsonToUrlAsync(
             new SeqLogRequest(entry),
             webRequest =>
         {
             if (!string.IsNullOrWhiteSpace(feature.ApiKey))
             {
                 webRequest.Headers.Add("X-Seq-ApiKey", feature.ApiKey);
             }
         });
     }
 }