public void When_custom_convertor_with_interface_types_should_deserialize_as_types()
        {
            var json     = EmbeddedResource.Read("Data.Articles.sample-with-inherited-types.json");
            var settings = new JsonApiSerializerSettings();

            settings.Converters.Add(new SubclassResourceObjectConverter <ArticleWithInterface.IResourceObject> (new Dictionary <string, Type>()
            {
                { "comments", typeof(ArticleWithInterface.CommentWithInterface) },
                { "comments-reply", typeof(ArticleWithInterface.CommentReplyWithInterface) },
                { "people", typeof(ArticleWithInterface.PersonWithInterface) },
                { "people-admin", typeof(ArticleWithInterface.PersonAdminWithInterface) }
            }));

            var articles = JsonConvert.DeserializeObject <ArticleWithInterface[]>(json, settings);

            var article = articles[0];

            Assert.IsType <ArticleWithInterface.CommentWithInterface>(article.Comments[0]);
            Assert.IsType <ArticleWithInterface.CommentWithInterface>(article.Comments[1]);
            Assert.IsType <ArticleWithInterface.CommentReplyWithInterface>(article.Comments[2]);
            Assert.Equal((ArticleWithInterface.CommentWithInterface)article.Comments[1], ((ArticleWithInterface.CommentReplyWithInterface)article.Comments[2]).ResponeTo);

            Assert.IsType <ArticleWithInterface.PersonAdminWithInterface>(article.Author);
            Assert.Equal(new[] { "edit", "delete" }, ((ArticleWithInterface.PersonAdminWithInterface)article.Author).AdministratorRights);
        }
        public void When_DateTime_should_deserialize_with_local_offset()
        {
            var json        = @"
{
    ""data"":{
        ""id"":""one"",
        ""attributes"":{
            ""DateTimeOffset"":""2017-01-01T12:00:00"",
            ""DateTime"":""2017-01-01T12:00:00"",
            ""NullableDateTimeOffset"":""2017-01-01T12:00:00"",
            ""NullableDateTime"":""2017-01-01T12:00:00""
        }
   }
}
";
            var settings    = new JsonApiSerializerSettings();
            var localOffset = new DateTimeOffset(new DateTime(0), TimeZoneInfo.Local.BaseUtcOffset).ToString("zzz");

            var dateTimes = JsonConvert.DeserializeObject <DateTimes>(json, settings);

            //Not happy with the behaviour to use local offset if an offset isnt defined
            //but it is the Json.NET default
            Assert.Equal($"2017-01-01T12:00:00{localOffset}", dateTimes.DateTimeOffset.ToString("yyyy-MM-ddTHH:mm:sszzz"));
            Assert.Equal("2017-01-01T12:00:00", dateTimes.DateTime.ToString("yyyy-MM-ddTHH:mm:ss"));
            Assert.Equal($"2017-01-01T12:00:00{localOffset}", dateTimes.NullableDateTimeOffset?.ToString("yyyy-MM-ddTHH:mm:sszzz"));
            Assert.Equal("2017-01-01T12:00:00", dateTimes.NullableDateTime?.ToString("yyyy-MM-ddTHH:mm:ss"));
        }
Beispiel #3
0
        public WebRequestResponse(IWebRequest response)
        {
            Code        = response.ResponseCode;
            RawResponse = response.RawResponse;

            try
            {
                StatusCode = (HttpStatusCode)this.Code;
                if (Code == HostErrorResponseCode)
                {
                    Errors = new Errors(HostErrorMessage);
                }
                else if (Code >= ErrorsResponseCodeStart)
                {
                    JsonConvert.PopulateObject(RawResponse, Errors = new Errors());
                }
            }
            catch
            {
                StatusCode = HttpStatusCode.Undefined;
            }

            settings = new JsonApiSerializerSettings();
            settings.Converters.Add(new GenericConverter());
        }
Beispiel #4
0
        public void When_object_root_with_array_should_deserialize()
        {
            var json       = EmbeddedResource.Read("Data.Articles.sample.json");
            var iterations = 50000;
            var settings   = new JsonApiSerializerSettings();

            //warmup
            var articles = JsonConvert.DeserializeObject <Article[]>(
                json,
                settings);

            var stopwatch = Stopwatch.StartNew();

            for (var i = 0; i < iterations; i++)
            {
                articles = JsonConvert.DeserializeObject <Article[]>(
                    json,
                    settings);
            }
            stopwatch.Stop();

            var elapsedMilliseconds = 1.0 * stopwatch.ElapsedMilliseconds / iterations;

            output.WriteLine($"{elapsedMilliseconds:0.00}ms per deserialization");
        }
        static void Main(string[] args)
        {
            try
            {
                var json = "{ \"data\": {  \"id\": \"1\",  \"type\" : \"product\",  \"attributes\" : {    \"name\": \"name\",    \"summary\": \"summary\"  } }}";

                var jsonApiSerializerSettings = new JsonApiSerializerSettings
                {
                    MissingMemberHandling = MissingMemberHandling.Error,
                };

                var product = JsonConvert.DeserializeObject <Product>(json, jsonApiSerializerSettings);

                Console.WriteLine($"Product id:{product.Id}");

                json = "{  \"id\": \"1\",  \"type\" : \"product\",  \"name\": \"name\", \"summary\": \"summary\" }";

                var jsonSerializerSettings = new JsonSerializerSettings
                {
                    MissingMemberHandling = MissingMemberHandling.Error,
                };

                product = JsonConvert.DeserializeObject <Product>(json, jsonSerializerSettings);

                Console.WriteLine(product.Id);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadLine();
        }
        public void When_DateTimeOffset_should_deserialize_with_offset()
        {
            var json      = @"
{
    ""data"":{
        ""id"":""one"",
        ""attributes"":{
            ""DateTimeOffset"":""2017-01-01T12:00:00+02:00"",
            ""DateTime"":""2017-01-01T12:00:00+02:00"",
            ""NullableDateTimeOffset"":""2017-01-01T12:00:00+02:00"",
            ""NullableDateTime"":""2017-01-01T12:00:00+02:00""
        }
   }
}
";
            var settings  = new JsonApiSerializerSettings();
            var dateTimes = JsonConvert.DeserializeObject <DateTimes>(json, settings);

            //Not happy with the behaviour to deserialize DateTime into DateTimeKind.Local,
            //but it is the Json.NET default
            Assert.Equal("2017-01-01T12:00:00+02:00", dateTimes.DateTimeOffset.ToString("yyyy-MM-ddTHH:mm:sszzz"));
            Assert.Equal("2017-01-01T10:00:00", dateTimes.DateTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss"));
            Assert.Equal("2017-01-01T12:00:00+02:00", dateTimes.NullableDateTimeOffset?.ToString("yyyy-MM-ddTHH:mm:sszzz"));
            Assert.Equal("2017-01-01T10:00:00", dateTimes.NullableDateTime?.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss"));
        }
Beispiel #7
0
        public void When_fields_controlled_by_jsonnet_nullignore_attributes_should_ignore_null()
        {
            var root = new DocumentRoot <ArticleWithNullIncludeProperties>
            {
                Data = new ArticleWithNullIncludeProperties
                {
                    Id       = "1234",
                    Title    = null, //default NullValueHandling
                    Author   = null, //NullValueHandling.Ignore
                    Comments = null  //NullValueHandling.Include
                }
            };


            var newSettings = new JsonApiSerializerSettings()
            {
                Formatting        = Formatting.Indented, //pretty print makes it easier to debug
                NullValueHandling = NullValueHandling.Include
            };
            var json = JsonConvert.SerializeObject(root, newSettings);

            Assert.Equal(@"
{
  ""data"": {
    ""type"": ""articles"",
    ""id"": ""1234"",
    ""links"": null,
    ""attributes"": {
      ""title"": null,
      ""comments"": null
    }
  }
}".Trim(), json);
        }
Beispiel #8
0
        public void When_customer_converter_with_default_type_name_should_use_custom_converter()
        {
            var settings = new JsonApiSerializerSettings()
            {
                Formatting = Formatting.Indented, //pretty print makes it easier to debug
            };

            settings.Converters.Add(new CustomTypeNameResourceObjectConverter(new Dictionary <Type, string>()
            {
                { typeof(ArticleWithNoType), "special-article-type" }
            }));

            var root = new DocumentRoot <ArticleWithNoType>
            {
                Data = new ArticleWithNoType
                {
                    Id = "1234",
                }
            };

            var json         = JsonConvert.SerializeObject(root, settings);
            var expectedjson = @"{
                ""data"": {
                    ""id"": ""1234"",
                    ""type"": ""special-article-type"",
                },
            }";

            Assert.Equal(expectedjson, json, JsonStringEqualityComparer.Instance);
        }
Beispiel #9
0
        public BattleriteClient Build(string token)
        {
            if (rateLimitPolicy == default(IRateLimitPolicy))
            {
                rateLimitPolicy = new RateLimitPolicy();
            }

            var jsonSerializerSettings = new JsonApiSerializerSettings();

            var requestUrlBuilder = new RequestUrlBuilder(EndPoints.BaseUrl, new List <IParameter>());

            var httpClient = new HttpClient();

            SetupHttpClient(token, httpClient);

            var requester = new Requester.Requester(httpClient, rateLimitPolicy);

            return(CreateBattleriteClient(
                       CreateOrGetAssetClient(),
                       CreateOrGetPlayerClient(
                           jsonSerializerSettings,
                           requestUrlBuilder,
                           requester,
                           CreateOrGetAssetClient()),
                       CreateOrGetMatchClient(requestUrlBuilder, requester)));
        }
        public void When_custom_convertor_with_interface_types_not_defined_should_error()
        {
            var json     = EmbeddedResource.Read("Data.Articles.sample-with-inherited-types.json");
            var settings = new JsonApiSerializerSettings();

            var error = Assert.Throws <JsonSerializationException>(() => JsonConvert.DeserializeObject <ArticleWithInterface[]>(json, settings));
        }
Beispiel #11
0
        public override string Serialize()
        {
            var settings = new JsonApiSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            };

            return(JsonConvert.SerializeObject(this, settings));
        }
        public void When_model_references_same_object_withdifferent_type_shoud_throw_exception()
        {
            var json     = EmbeddedResource.Read("Data.Articles.sample-error-two-class-single-include.json");
            var settings = new JsonApiSerializerSettings();

            var exception = Assert.Throws <Newtonsoft.Json.JsonSerializationException>(() => JsonConvert.DeserializeObject <Article[]>(
                                                                                           json,
                                                                                           settings));
        }
        public void When_model_does_not_match_json_should_throw_serialization_exception()
        {
            var json     = EmbeddedResource.Read("Data.Articles.sample-error-model-not-match-values.json");
            var settings = new JsonApiSerializerSettings();

            var exception = Assert.Throws <Newtonsoft.Json.JsonSerializationException>(() => JsonConvert.DeserializeObject <Article[]>(
                                                                                           json,
                                                                                           settings));
        }
        public JsonApiInputFormatter(ILogger logger, JsonApiSerializerSettings serializerSettings, ArrayPool <char> charPool, ObjectPoolProvider objectPoolProvider, MvcOptions options, MvcJsonOptions jsonOptions)
            : base(logger, serializerSettings, charPool, objectPoolProvider, options, jsonOptions)
        {
            SupportedMediaTypes.Clear();
            SupportedEncodings.Clear();

            SupportedMediaTypes.Add(Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/vnd.api+json"));
            SupportedEncodings.Add(System.Text.Encoding.UTF8);
            SupportedEncodings.Add(System.Text.Encoding.Unicode);
        }
        public JsonApiOutputFormatter(JsonApiSerializerSettings serializerSettings, ArrayPool <char> charPool)
            : base(serializerSettings, charPool)
        {
            SupportedMediaTypes.Clear();
            SupportedEncodings.Clear();

            SupportedMediaTypes.Add(Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/vnd.api+json"));
            SupportedEncodings.Add(System.Text.Encoding.UTF8);
            SupportedEncodings.Add(System.Text.Encoding.Unicode);
        }
        public void Setup()
        {
            Randomizer.Seed = new Random(56178921);

            options         = new JsonSerializerOptions();
            jsonApiOptions  = new JsonSerializerOptions().AddJsonApi();
            jsonApiSettings = new JsonApiSerializerSettings();

            data = TestCases.Get(Case);
        }
        public void When_object_root_with_array_should_deserialize()
        {
            var json = EmbeddedResource.Read("Data.Articles.sample.json");

            var settings = new JsonApiSerializerSettings();
            var articles = JsonConvert.DeserializeObject <Article[]>(
                json,
                new JsonApiSerializerSettings());

            AssertArticlesMatchData(articles);
        }
        public void When_id_not_a_string_should_throw()
        {
            var json     = EmbeddedResource.Read("Data.Articles.sample-error-id-not-string.json");
            var settings = new JsonApiSerializerSettings();

            var exception = Assert.Throws <JsonApiFormatException>(() => JsonConvert.DeserializeObject <Article[]>(
                                                                       json,
                                                                       settings));

            Assert.Equal("data[0].relationships.comments.data[1].id", exception.Path);
        }
        public void When_data_element_missing_should_throw()
        {
            var json     = EmbeddedResource.Read("Data.Articles.sample-error-missing-data-element.json");
            var settings = new JsonApiSerializerSettings();

            var exception = Assert.Throws <JsonApiFormatException>(() => JsonConvert.DeserializeObject <Article[]>(
                                                                       json,
                                                                       settings));

            Assert.Equal("data[0].relationships.author", exception.Path);
        }
        public void When_attributes_not_object_should_throw()
        {
            var json     = EmbeddedResource.Read("Data.Articles.sample-error-attributes-not-object.json");
            var settings = new JsonApiSerializerSettings();

            var exception = Assert.Throws <JsonApiFormatException>(() => JsonConvert.DeserializeObject <Article[]>(
                                                                       json,
                                                                       settings));

            Assert.Equal("data[0].attributes", exception.Path);
        }
Beispiel #21
0
        public void When_array_deserize_as_object_should_throw_exception()
        {
            var json     = EmbeddedResource.Read("Data.Articles.sample.json");
            var settings = new JsonApiSerializerSettings();

            var exception = Assert.Throws <JsonApiFormatException>(() => JsonConvert.DeserializeObject <Article>(
                                                                       json,
                                                                       settings));

            Assert.Equal("data", exception.Path);
        }
        public void When_resource_object_custom_convertor_defined_with_attributes_should_deserialize_as_types()
        {
            var json     = EmbeddedResource.Read("Data.Articles.sample-with-inherited-types.json");
            var settings = new JsonApiSerializerSettings();

            var articles = JsonConvert.DeserializeObject <ArticleWithResourceObjectCustomConvertor[]>(json, settings);

            var article = articles[0];

            Assert.IsType <PersonAdmin>(article.Author);
            Assert.Equal(new[] { "edit", "delete" }, ((PersonAdmin)article.Author).AdministratorRights);
        }
Beispiel #23
0
        public void When_custom_convertor_should_use_on_attributes()
        {
            var settings = new JsonApiSerializerSettings()
            {
                Formatting = Formatting.Indented, //pretty print makes it easier to debug
            };

            var root = new Timer
            {
                Id       = "root",
                Duration = TimeSpan.FromSeconds(42),
                SubTimer = new List <Timer>
                {
                    new Timer
                    {
                        Id       = "sub1",
                        Duration = TimeSpan.FromSeconds(142)
                    }
                }
            };


            var json = JsonConvert.SerializeObject(root, settings);

            Assert.Equal(@"{
  ""data"": {
    ""type"": ""timer"",
    ""id"": ""root"",
    ""attributes"": {
                ""duration"": 42
    },
    ""relationships"": {
                ""subTimer"": {
                    ""data"": [
                      {
            ""id"": ""sub1"",
                        ""type"": ""timer""
          }
        ]
      }
    }
  },
  ""included"": [
    {
      ""type"": ""timer"",
      ""id"": ""sub1"",
      ""attributes"": {
        ""duration"": 142
      }
    }
  ]
}", json, JsonStringEqualityComparer.Instance);
        }
Beispiel #24
0
        internal BaseEndpoint(IRestClient client, string endpointPath)
        {
            EndpointPath = endpointPath;
            this.Client  = client;

            JsonSettings = new JsonApiSerializerSettings()
            {
                ContractResolver = new JsonApiContractResolver()
                {
                    NamingStrategy = new SnakeCaseNamingStrategy(true, false)
                }
            };
        }
Beispiel #25
0
        public BaseEndpoint(string clientId, string clientSecret, string baseUrl)
        {
            Client = new RestClient(baseUrl);
            Client.Authenticator = new HttpBasicAuthenticator(clientId, clientSecret);

            JsonSettings = new JsonApiSerializerSettings()
            {
                ContractResolver = new JsonApiContractResolver()
                {
                    NamingStrategy = new SnakeCaseNamingStrategy(true, false)
                }
            };
        }
Beispiel #26
0
        public void When_member_converter_with_default_type_name_should_use_custom_converter()
        {
            var settings = new JsonApiSerializerSettings()
            {
                Formatting = Formatting.Indented, //pretty print makes it easier to debug
            };


            var root = new DocumentRoot <ArticleWithCustomConverter>
            {
                Data = new ArticleWithCustomConverter
                {
                    Id     = "1234",
                    Author = new PersonWithNoType()
                    {
                        Id        = "person-1234",
                        FirstName = "typeless"
                    }
                }
            };

            var json         = JsonConvert.SerializeObject(root, settings);
            var expectedjson = @"{
                ""data"": {
                    ""id"": ""1234"",
                    ""type"": ""articlewithcustomconverter"",
                    ""relationships"": {
                        ""author"": {
                            ""data"": { 
                                ""id"":""person-1234"", 
                                ""type"":""special-author""
                            }
                        }
                    }
                },
                ""included"" : [
                    {
                        ""id"": ""person-1234"",
                        ""type"": ""special-author"",
                        ""attributes"":{
                            ""first-name"": ""typeless""
                        }

                    }
                ]
            }";

            Assert.Equal(expectedjson, json, JsonStringEqualityComparer.Instance);
        }
Beispiel #27
0
        public void When_override_generate_default_type_name_should_use_customer_type_name()
        {
            var settings = new JsonApiSerializerSettings(new ShoutingClassNameObjectConverter())
            {
                Formatting = Formatting.Indented, //pretty print makes it easier to debug
            };

            var root = new DocumentRoot <ArticleWithNoType>
            {
                Data = new ArticleWithNoType
                {
                    Id     = "1234",
                    Author = new Person()
                    {
                        Id        = "jdoe",
                        FirstName = "John",
                        LastName  = "Doe"
                    }
                }
            };

            var json = JsonConvert.SerializeObject(root, settings);

            Assert.Equal(@"
{
  ""data"": {
            ""type"": ""ARTICLEWITHNOTYPE"",
            ""id"": ""1234"",
            ""relationships"": {
                ""author"": {
                    ""data"": {
                        ""id"": ""jdoe"",
                        ""type"": ""people""
                    }
                }
            }
        },
        ""included"": [
        {
            ""type"": ""people"",
            ""id"": ""jdoe"",
            ""attributes"": {
                ""first-name"": ""John"",
                ""last-name"": ""Doe""
            }
        }
        ]
    }", json, JsonStringEqualityComparer.Instance);
        }
Beispiel #28
0
        public void When_id_invalid_type_and_null_and_show_nulls_should_throw()
        {
            var root = new DocumentRoot <ArticleWithIdType <Task> >
            {
                Data = new ArticleWithIdType <Task>
                {
                    Id    = null,
                    Title = "My title"
                }
            };

            var showNullSettings = new JsonApiSerializerSettings {
                NullValueHandling = NullValueHandling.Include
            };

            Assert.Throws <JsonApiFormatException>(() => JsonConvert.SerializeObject(root, showNullSettings));
        }
        public void When_dates_non_date_strings()
        {
            var json     = @"
{
    ""data"":{
        ""id"":""one"",
        ""attributes"":{
            ""DateTimeOffset"":""hello world"",
            ""DateTime"":""hello world"",
            ""NullableDateTimeOffset"":""hello world"",
            ""NullableDateTime"":""hello world""
        }
   }
}
";
            var settings = new JsonApiSerializerSettings();

            Assert.Throws <JsonSerializationException>(() => JsonConvert.DeserializeObject <DateTimes>(json, settings));
        }
        public void When_dates_are_null_should_error()
        {
            var json     = @"
{
    ""data"":{
        ""id"":""one"",
        ""attributes"":{
            ""DateTimeOffset"":null,
            ""DateTime"":null,
            ""NullableDateTimeOffset"":null,
            ""NullableDateTime"":null
        }
   }
}
";
            var settings = new JsonApiSerializerSettings();

            Assert.Throws <JsonSerializationException>(() => JsonConvert.DeserializeObject <DateTimes>(json, settings));
        }